LeetCode 刷题笔录 Add Two Numbers
2013-10-02 15:04
363 查看
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
这题看起来没啥好说的,挨个顺序扫描就行了。要注意null的位置以及进位的问题。我的代码通不过测试。。。输入{9},{9}显示我的程序返回是{9},{1},而答案应该是{8},{1}。但是我把这代码在自己机器上用eclipse编译完了答案是正确的。。。也看不出自己哪里有错,可能是leetcode编译的问题吧。先记下来再说。
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
这题看起来没啥好说的,挨个顺序扫描就行了。要注意null的位置以及进位的问题。我的代码通不过测试。。。输入{9},{9}显示我的程序返回是{9},{1},而答案应该是{8},{1}。但是我把这代码在自己机器上用eclipse编译完了答案是正确的。。。也看不出自己哪里有错,可能是leetcode编译的问题吧。先记下来再说。
private boolean carry = false; //set the flag to true if a carry is needed public ListNode addTwoNumbers(ListNode l1, ListNode l2) { // Start typing your Java solution below // DO NOT write main() function int first = add(l1.val, l2.val); ListNode previous = new ListNode(first); //the first node of the answer linked list ListNode header = previous; for(l1 = l1.next, l2 = l2.next; l1 != null && l2 != null; l1 = l1.next, l2 = l2.next){ previous = previous.next = new ListNode(add(l1.val, l2.val)); } if(l1 == null && l2 == null){ if(carry){ previous = previous.next = new ListNode(1); } } else if(l1 == null){ while(l2 != null){ previous = previous.next = new ListNode(l2.val); l2 = l2.next; } } else if(l2 == null){ while(l1 != null){ previous = previous.next = new ListNode(l1.val); l1 = l1.next; } } return header; } /** * add the two numbers * return the last digit of the result of the sum of the two numbers * if the sum is larger than 10, set the carry flag to true */ private int add(int a, int b){ int result = a + b; if(carry){ result++; } if(result < 10){ carry = false; return result; } else{ result = result % 10; carry = true; return result; } }
相关文章推荐
- leetcode 2. Add Two Numbers python实现的理解,结点,单链表的应用,大数,进位的问题
- 【LeetCode】Add Two Numbers
- (leetcode)2. 两个链表相加Add Two Numbers--Java
- [LeetCode] 2. Add Two Numbers
- [C语言][LeetCode][2]Add Two Numbers
- leetcode 2. Add Two Numbers
- [leetcode]Add Two Numbers @ Python
- leetcode:Add Two Numbers 【Java】
- LeetCode-Add Two Numbers II
- leetCode | Add Two Numbers
- LeetCode(2) Add Two Numbers实现
- LeetCode -- Add Two Numbers
- leetcode-2 Add Two Numbers
- leetcode解题方案--002--AddTwoNumbers
- [LeetCode] Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode AddTwoNumbers
- LeetCode2——Add Two Numbers(两个链表中的数字相加,形成新链表)
- [LeetCode]Add Two Numbers
- LeetCode_2 Add Two Numbers(链表)