Leet Code add two number
2015-02-09 13:45
267 查看
add two number
题目要求: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
public class ListNode { int val; ListNode next=null; ListNode(int x) { val = x; next = null; } }
.
public class Solution { public static void main(String[] args) { ListNode listNodeL1=new ListNode(1); ListNode listNodeL1_2=new ListNode(2); ListNode listNodeL1_3=new ListNode(3); listNodeL1.next=listNodeL1_2; listNodeL1_2.next=listNodeL1_3; listNodeL1_3.next=null; ListNode listNodeL2=new ListNode(1); ListNode listNodeL2_2=new ListNode(2); ListNode listNodeL2_3=new ListNode(3); listNodeL2.next=listNodeL2_2; listNodeL2_2.next=listNodeL2_3; listNodeL2_3.next=null; Solution solution = new Solution(); ListNode rs= solution.addTwoNumbers(listNodeL1,listNodeL2); while (rs!=null){ System.out.println(rs.val); rs=rs.next; } } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode rs=new ListNode(0); ListNode cur=rs; int carry = 0; int i = 0; int j = 0; while (l1 != null || l2 != null) { if (l1 != null) { i = l1.val; l1=l1.next; } if (l2 != null) { j = l2.val; l2 = l2.next; } int sum = i + j + carry; //如果大于10 进位 cur.next=new ListNode(sum%10); //创建一个新的节点 cur=cur.next; //把下个节点和当前节点连起来 carry=sum/10;//算进位 } if(carry>0) cur.next=new ListNode(carry); return rs.next; } }
相关文章推荐
- Leet Code Medium 2 add two numbers
- LeeCode---Add Two Numbers
- leecode algo2: Add Two Numbers (Java)
- Leet Code OJ 2. Add Two Numbers [Difficulty: Medium]
- 2 Add Two Numbers LeeCode
- LeetCode Online Judge 题目C# 练习 - Add two number
- leecode 解题总结:160. Intersection of Two Linked Lists
- leecode algo4: Median of Two Sorted Arrays (Java)
- leecode 解题总结:349. Intersection of Two Arrays
- use MyButton is simple,only add two file and then add some code just bellow in any dlg src declear the button control and will ok!
- LeetCode笔记 -- Add Two Number
- LeetCode- Add two number I
- 【leetcode】 add two number
- LeetCode Week1: Two Sum、Add Two Numbers、Median of Two Sorted Arrays
- leetoj Add Two Numbers
- Leetcode 2. Add Two Number
- Leet Code 2 Add Two Numbers - 链表表示的两个数求和 - Java
- 2.Add Two Number
- Add two linenumber
- leetcode add two number