-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdouble-a-number-represented-as-a-linked-list.java
54 lines (50 loc) · 1.43 KB
/
double-a-number-represented-as-a-linked-list.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Definition for singly-linked list.
* 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 doubleIt(ListNode head) {
ListNode head1 = new ListNode();
head1.next = head;
ListNode left = head1;
ListNode right = head;
while (right != null) {
if (right.val * 2 >= 10) {
left.val += 1;
}
right.val = (right.val * 2) % 10;
left = left.next;
right = right.next;
}
return head1.val > 0 ? head1 : head;
}
}
// recursion beats 55%
// /**
// * Definition for singly-linked list.
// * 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 doubleIt(ListNode head) {
// int carry=recursivecarry(head);
// return carry==0 ? head : new ListNode(carry,head);
// }
// public int recursivecarry(ListNode head){
// if(head==null) return 0;
// int sum=recursivecarry(head.next)+head.val*2;
// head.val=sum%10;
// return sum/10;
// }
// }