1290. Convert Binary Number in A Linked List to Integer #
题目 #
给定单链表头节点head
,已知此链表是一个整数数字的二进制表示形式,链表中每个节点的值非0即1。返回链表所表示数字的十进制值。
思路 #
代码 #
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null, cur = head, next = head.next;
while(cur != null) {
cur.next = prev;
prev = cur;
cur = next;
if (next != null) next = next.next;
}
return prev;
}
public int getDecimalValue(ListNode head) {
ListNode newHead = reverseList(head);
int decimal = 0, digit = 0;
ListNode ptr = newHead;
while (ptr != null) {
decimal += Math.pow(2, digit) * ptr.val;
digit += 1;
ptr = ptr.next;
}
reverseList(newHead);
return decimal;
}
}