Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
Open
@grandyang

Description

@grandyang
Issue body actions

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 打赏


---|---

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.