标签:bsp col tiny contain not sum empty red lists
题目: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
输入那里 为 342 + 564 输出为 807。
这题难度为中等难度,其实这题难度比较低,就用小学做加减法的思路做 ,同位相加,满10进1。
1 package cn.tiny77.leetcodepart1; 2 3 public class Solution1 { 4 5 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 6 int jinwei = 0; 7 ListNode result = null; 8 ListNode temp = null; 9 while(l1!=null || l2!=null) { 10 int val = (l1==null?0:l1.val) + (l2==null?0:l2.val) + jinwei; 11 jinwei = val > 9 ? 1: 0; 12 val %= 10; 13 if(result == null) { 14 result = new ListNode(val); 15 temp = result; 16 }else { 17 temp.next = new ListNode(val); 18 temp = temp.next; 19 } 20 if(l1!=null) l1 = l1.next; 21 if(l2!=null) l2 = l2.next; 22 } 23 if(jinwei!=0) { 24 temp.next = new ListNode(jinwei);26 } 27 return result; 28 } 29 30 }
标签:bsp col tiny contain not sum empty red lists
原文地址:http://www.cnblogs.com/qins/p/7496401.html