-
Notifications
You must be signed in to change notification settings - Fork 5
/
AddOne.java
110 lines (102 loc) · 2.34 KB
/
AddOne.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*https://practice.geeksforgeeks.org/problems/add-1-to-a-number-represented-as-linked-list/1/*/
/*Pratik's solution*/
class Solution
{
static int i=0;
public static Node addOne(Node head)
{
//code here.
if(head == null)return head;
Node cur = new Node(-1);
int res = 0;
if(head.next == null)
{
res = head.data+1;
head.data = res%10;
cur.data = res/10;
if(i==0)
{
if(cur.data>0)
{
cur.next = head;
head = cur;
}
return head;
}
return cur;
}
i++;
res = head.data+addOne(head.next).data;
i--;
head.data = res%10;
cur.data = res/10;
if(i==0)
{
if(cur.data>0)
{
cur.next = head;
head = cur;
}
return head;
}
return cur;
}
}
/*Prateekshya's solution*/
//used recursion
class Solution
{
static int carry;
public static Node addOne(Node head)
{
carry = 0; //initialize carry to 0
//for single node
if (head.next == null)
{
head.data += 1;
if (head.data > 9)
{
head.data -= 10;
Node newHead = new Node(1);
newHead.next = head;
return newHead;
}
return head;
}
//recursion call
head = getNewList(head);
//if still carry is present, add a new node and return
if (carry > 0)
{
Node newHead = new Node(1);
newHead.next = head;
return newHead;
}
return head;
}
public static Node getNewList(Node head)
{
//base case
if (head.next == null)
{
head.data += 1;
head = check(head);
return head;
}
/*recursion call*/
head.next = getNewList(head.next);
head.data += carry;
head = check(head);
return head;
}
public static Node check(Node head)
{
if (head.data > 9)
{
head.data -= 10;
carry = 1;
}
else carry = 0;
return head;
}
}