Convert Binary Number in a Linked List to Integer LeetCode solution in Java

1
/**
2
* Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode() {}
3
* ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val;
4
* this.next = next; } }
5
*/
6
class Solution {
7
public int getDecimalValue(ListNode head) {
8
head = reverse(head);
9
int ans = 0;
10
int pow = 0;
11
ListNode temp = head;
12
while (temp != null) {
13
ans = ans + temp.val * (int) Math.pow(2, pow++);
14
temp = temp.next;
15
}
16

17
return ans;
18
}
19

20
public ListNode reverse(ListNode head) {
21
ListNode prev = null;
22
ListNode pres = head;
23
ListNode Next = pres.next;
24

25
while (pres != null) {
26
pres.next = prev;
27
prev = pres;
28
pres = Next;
29
if (Next != null) {
30
Next = Next.next;
31
}
32
}
33

34
head = prev;
35
return head;
36
}
37
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0