Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 1290. Convert Binary Number in a Linked List to Integer #1290

Open
grandyang opened this issue May 30, 2019 · 0 comments
Open

[LeetCode] 1290. Convert Binary Number in a Linked List to Integer #1290

grandyang opened this issue May 30, 2019 · 0 comments

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019

Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.

Return the  decimal value  of the number in the linked list.

Example 1:

Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10

Example 2:

Input: head = [0]
Output: 0

Constraints:

  • The Linked List is not empty.
  • Number of nodes will not exceed 30.
  • Each node's value is either 0 or 1.

这道题让把一个用链表表示的二进制数转为一个整型数,链表的结点值只有0或1,而且首结点是二进制数的最高位。这题主要考察两点,一个是二进制数如何转十进制数,另一个是遍历链表。都不是太难,直接遍历链表,每次先将 res 自乘以2,因为新加一个结点,说明之前的每一位都要左移一位,所以要乘以2,然后再加上当前结点值,同时将 head 指针右移一位即可,参见代码如下:

class Solution {
public:
    int getDecimalValue(ListNode* head) {
        int res = 0;
        while (head) {
            res = res * 2 + head->val;
            head = head->next;
        }
        return res;
    }
};

Github 同步地址:

#1290

参考资料:

https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/

https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/discuss/629087/Detailed-explanation-Java-%3A-faster-than-100.00

LeetCode All in One 题目讲解汇总(持续更新中...)

喜欢请点赞,疼爱请打赏❤️~.~

微信打赏

|

Venmo 打赏


---|---

@grandyang grandyang changed the title [LeetCode] 1290. Missing Problem [LeetCode] 1290. Convert Binary Number in a Linked List to Integer Apr 15, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant