Skip to content

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

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  int getDecimalValue(ListNode* head) {
    int ans = 0;

    for (; head; head = head->next)
      ans = ans * 2 + head->val;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public int getDecimalValue(ListNode head) {
    int ans = 0;

    for (; head != null; head = head.next)
      ans = ans * 2 + head.val;

    return ans;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def getDecimalValue(self, head: ListNode) -> int:
    ans = 0

    while head:
      ans = ans * 2 + head.val
      head = head.next

    return ans