leetCode练习(2)
2016-09-11 17:58
260 查看
题目:Add Two Numbers
难度:medium
问题描述:
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
错误点:分别计算出l1和l2代表的int值再相加,这是错误解法,因为int会溢出。
解题思路:每位相加注意进位即可。代码如下:
难度:medium
问题描述:
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
错误点:分别计算出l1和l2代表的int值再相加,这是错误解法,因为int会溢出。
解题思路:每位相加注意进位即可。代码如下:
public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head,tail,temp,t1,t2; int x,jinwei=0; t1=l1;t2=l2; tail=new ListNode(0); head=new ListNode(0); if(t1==null) t1=new ListNode(0); if(t2==null) t2=new ListNode(0); //对第一个节点进行初始化 x=t1.val+t2.val+jinwei; if(x<10){ jinwei=0; }else{ x=x-10; jinwei=1; } head=new ListNode(x); tail=head; t1=t1.next; t2=t2.next; //l1,l2尾指针归位 while(true){ if(t1==null&&t2==null&&jinwei==0){ return head; }else{ if(t1==null) t1=new ListNode(0); if(t2==null) t2=new ListNode(0); x=t1.val+t2.val+jinwei; if(x<10){ jinwei=0; }else{ x=x-10; jinwei=1; } temp=new ListNode(x); tail.next=temp; tail=tail.next; t1=t1.next; t2=t2.next; } } } }
相关文章推荐
- 『LeetCode』练习第五弹_算法7,8题
- leetCode练习(7)
- LeetCode Online Judge 题目C# 练习 - Jump Game
- LeetCode Online Judge 题目C# 练习 - Length of Last Word
- leetCode练习(93)
- leetCode练习(95)
- LeetCode Online Judge 题目C# 练习 - Permutations
- LeetCode Online Judge 题目C# 练习 - Regular Expression Matching
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List II
- LeetCode Online Judge 题目C# 练习 - Two Sum
- leetCode练习(104)
- leetCode练习(110)
- LeetCode练习记录2017/12/9
- leetCode练习(118)
- leetCode练习(134)(
- LeetCode练习-字符串
- LeetCode编程练习 - Happy Number学习心得
- [编程练习]ZigZag Conversion <LeetCode-6>
- leetcode练习
- leetCode练习(47)