Skip to content

Instantly share code, notes, and snippets.

@cshijiel
Created September 4, 2017 12:47
Show Gist options
  • Save cshijiel/0b9db66d9afd0fe0f86bc5d194fcf6fa to your computer and use it in GitHub Desktop.
Save cshijiel/0b9db66d9afd0fe0f86bc5d194fcf6fa to your computer and use it in GitHub Desktop.
Add Two Numbers
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;
}
}
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;
}
@cshijiel
Copy link
Author

cshijiel commented Sep 4, 2017

  1. ?表达式的运用,无需if判空,这个想到了,但是没有具体的实现方案,运用不熟悉
  2. 命名的方式:carry、sum、p、q、current等
  3. 除法直接算出carry
  4. next其实对应答案的current
  5. curr.next = new ListNode(carry); 这种写法更为规范

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment