File tree 1 file changed +14
-16
lines changed
1 file changed +14
-16
lines changed Original file line number Diff line number Diff line change 3
3
* public class ListNode {
4
4
* int val;
5
5
* 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; }
7
9
* }
8
10
*/
9
11
class Solution {
10
12
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 ;
17
18
}
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 ;
26
24
}
27
- return count ;
25
+ return decimalValue ;
28
26
}
29
27
}
You can’t perform that action at this time.
0 commit comments