代码改变世界

Add Two Numbers

2011-12-23 10:12  OntheMars  阅读(265)  评论(0编辑  收藏  举报

First post here, : )

Problem

Add Two Numbers from http://www.leetcode.com/onlinejudge

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

This problem is easy, it 's a practice for traversing the list by using ListNode class the problem given. 

1: go through two list

2:combine those two list(need ti be careful for handling Carry digit and one number is longer than other  )

3:print answer

public class ListNode
{
int val;
ListNode next;

ListNode(int x)
{
val = x;
next = null;
}

public ListNode addTwoNumbers(ListNode l1, ListNode l2)
{
ListNode head = new ListNode(-1), p = head;

ListNode A = l1;
ListNode B = l2;

int jin = 0;
while ((A != null || B != null) || jin > 0)
{
int x = 0;

if (A == null && B == null)
{
ListNode tmp = new ListNode(jin);
p.next = tmp;
p = tmp;
break;
}

if (A == null && B != null)
{
x = B.val + jin;
jin = x / 10;
x = x % 10;

ListNode tmp = new ListNode(x);
p.next = tmp;
p = tmp;
B = B.next;
continue;
}
if (A != null && B == null)
{
x = A.val + jin;
jin = x / 10;
x = x % 10;
ListNode tmp = new ListNode(x);
p.next = tmp;
p = tmp;
A = A.next;
continue;
}
x = A.val + B.val + jin; jin = x / 10;
x = x % 10;
ListNode tmp = new ListNode(x);
p.next = tmp;
p = tmp;
A = A.next;
B = B.next;
}
return head.next;
}

}