Created
September 4, 2017 12:47
-
-
Save cshijiel/0b9db66d9afd0fe0f86bc5d194fcf6fa to your computer and use it in GitHub Desktop.
Add Two Numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Add; | |
/** | |
* Created by chenpeng on 2017/9/4. | |
* | |
* @version 1.0 | |
*/ | |
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { val = x; } | |
* } | |
*/ | |
public class ListNode { | |
int val; | |
ListNode next; | |
ListNode(int x) { | |
val = x; | |
} | |
} | |
class Solution { | |
public static void main(String[] args) { | |
ListNode l1 = new ListNode(1); | |
ListNode l2 = new ListNode(9); | |
l2.next = new ListNode(9); | |
ListNode listNode = addTwoNumbers(l1, l2); | |
System.out.println(listNode); | |
} | |
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { | |
ListNode result = new ListNode(0); | |
ListNode listNode = result; | |
int i = 0; | |
while (l1 != null || l2 != null) { | |
ListNode next = new ListNode(0); | |
int temp = 0; | |
if (l1 != null) { | |
temp += l1.val; | |
l1 = l1.next; | |
} | |
if (l2 != null) { | |
temp += l2.val; | |
l2 = l2.next; | |
} | |
int val = temp % 10 + i; | |
next.val = val % 10; | |
if (val > 9 || temp > 9) { | |
i = 1; | |
} else { | |
i = 0; | |
} | |
listNode.next = next; | |
listNode = listNode.next; | |
} | |
if (i > 0) { | |
listNode.next = new ListNode(1); | |
} | |
return result.next; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { | |
ListNode dummyHead = new ListNode(0); | |
ListNode p = l1, q = l2, curr = dummyHead; | |
int carry = 0; | |
while (p != null || q != null) { | |
int x = (p != null) ? p.val : 0; | |
int y = (q != null) ? q.val : 0; | |
int sum = carry + x + y; | |
carry = sum / 10; | |
curr.next = new ListNode(sum % 10); | |
curr = curr.next; | |
if (p != null) p = p.next; | |
if (q != null) q = q.next; | |
} | |
if (carry > 0) { | |
curr.next = new ListNode(carry); | |
} | |
return dummyHead.next; | |
} |
Author
cshijiel
commented
Sep 4, 2017
- ?表达式的运用,无需if判空,这个想到了,但是没有具体的实现方案,运用不熟悉
- 命名的方式:carry、sum、p、q、current等
- 除法直接算出carry
- next其实对应答案的current
- curr.next = new ListNode(carry); 这种写法更为规范
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment