Chinaunix首页 | 论坛 | 博客
  • 博客访问: 80461
  • 博文数量: 29
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 225
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-06 15:31
文章分类

全部博文(29)

文章存档

2015年(18)

2014年(11)

我的朋友

分类: Java

2015-01-17 11:38:15

题目:

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
解法:

点击(此处)折叠或打开

  1. /**
  2.  * Definition for singly-linked list.
  3.  * public class ListNode {
  4.  * int val;
  5.  * ListNode next;
  6.  * ListNode(int x) {
  7.  * val = x;
  8.  * next = null;
  9.  * }
  10.  * }
  11.  */
  12. public class Solution {
  13.     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  14.         ListNode prev = new ListNode(0);
  15.         ListNode head = prev;
  16.         int carry = 0;
  17.         while (l1 != null || l2 != null || carry != 0) {
  18.             ListNode cur = new ListNode(0);
  19.             int sum = ((l2 == null) ? 0 : l2.val) + ((l1 == null) ? 0 : l1.val) + carry;
  20.             cur.val = sum % 10;
  21.             carry = sum / 10;
  22.             prev.next = cur;
  23.             prev = cur;

  24.             l1 = (l1 == null) ? l1 : l1.next;
  25.             l2 = (l2 == null) ? l2 : l2.next;
  26.         }
  27.         return head.next;
  28.     }
  29. }

        


阅读(676) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~