2. Add Two Numbers

来源:互联网 发布:mac系统自动重装系统 编辑:程序博客网 时间:2024/05/23 00:09

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8


package November;public class AddTwoNumbers {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {ListNode result=new ListNode(0);addTwoNumbers(l1,l2,result);return result;}public void addTwoNumbers(ListNode l1, ListNode l2,ListNode res_tmp) {int carry=0;while (l1 != null || l2 != null) {//考虑判断条件,如果分别加两个循环,没有这个简洁int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val)//考虑判断条件+ carry;//考虑carryint current = sum % 10;carry = sum / 10;res_tmp.val = current;if (l1 != null) {//conditionl1 = l1.next;}if (l2 != null) {//conditionl2 = l2.next;}if (l1 != null || l2 != null || carry != 0) {//conditionres_tmp.next = new ListNode(0);res_tmp = res_tmp.next;}}if(carry!=0){//conditionres_tmp.val=carry;res_tmp.next=null;}}public class ListNode {int val;ListNode next;ListNode(int x) {val = x;}}}