0
点赞
收藏
分享

微信扫一扫

LeetCode知识点总结 - 1290

_刘彦辉 2022-01-06 阅读 35

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

考点难度
Linked ListEasy
题目

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.

思路

每遇到一个新node,把之前的值乘2再加上node的值。乘以2等于bit manipulation中的把数字整个向左移动一位。

答案
public int getDecimalValue(ListNode head) {
        int num = head.val;
        while (head.next != null) {
            num = num * 2 + head.next.val;
            head = head.next;    
        }
        return num;
}
举报

相关推荐

0 条评论