Skip to content

Commit b9ae48f

Browse files
authored
Update Convert Binary Number in a Linked List to Integer.java
1 parent 73ee8a5 commit b9ae48f

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed

Easy/Convert Binary Number in a Linked List to Integer.java

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,25 @@
33
* public class ListNode {
44
* int val;
55
* ListNode next;
6-
* ListNode(int x) { val = x; }
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
79
* }
810
*/
911
class Solution {
1012
public int getDecimalValue(ListNode head) {
11-
int length = getLength(head);
12-
int sum = 0;
13-
while (head != null) {
14-
sum += ((int) Math.pow(2, length - 1)) * head.val;
15-
length--;
16-
head = head.next;
13+
int nodeLength = -1;
14+
ListNode curr = head;
15+
while (curr != null) {
16+
nodeLength++;
17+
curr = curr.next;
1718
}
18-
return sum;
19-
}
20-
21-
private int getLength(ListNode head) {
22-
int count = 0;
23-
while (head != null) {
24-
count++;
25-
head = head.next;
19+
int decimalValue = 0;
20+
curr = head;
21+
while (curr != null) {
22+
decimalValue += curr.val * Math.pow(2, nodeLength--);
23+
curr = curr.next;
2624
}
27-
return count;
25+
return decimalValue;
2826
}
2927
}

0 commit comments

Comments
 (0)