File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Name - Add Two Numbers
3
+ Link - https://leetcode.com/problems/add-two-numbers/
4
+ Time Complexity - O(m + n)
5
+ Space Complexity - o(1)
6
+ Note - make use of modulo (get remainder) and division (get quotient)
7
+ */
8
+
9
+ class Solution {
10
+ public ListNode addTwoNumbers (ListNode first , ListNode second ) {
11
+ int q = 0 ;
12
+ int r = 0 ;
13
+ int sum = 0 ;
14
+ ListNode head = null ;
15
+ ListNode temp = null ;
16
+ while (first != null || second != null ) {
17
+ sum = q + (((first != null ) ? first .val : 0 ) + ((second != null ) ? second .val : 0 ));
18
+ r = sum % 10 ;
19
+ q = sum / 10 ;
20
+ ListNode newNode = new ListNode (r );
21
+ if (head == null ) {
22
+ head = newNode ;
23
+ } else {
24
+ temp = head ;
25
+ while (temp .next !=null ){
26
+ temp =temp .next ;
27
+ }
28
+ temp .next = newNode ;
29
+ newNode .next = null ;
30
+ }
31
+ if (first != null ) {
32
+ first = first .next ;
33
+ }
34
+ if (second != null ) {
35
+ second = second .next ;
36
+ }
37
+ }
38
+ if (q >0 ){
39
+ ListNode newNode = new ListNode (q );
40
+ temp = head ;
41
+ while (temp .next !=null ){
42
+ temp =temp .next ;
43
+ }
44
+ temp .next = newNode ;
45
+ newNode .next = null ;
46
+ }
47
+ return head ;
48
+ }
49
+ }
You can’t perform that action at this time.
0 commit comments