码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 002 两个数相加

时间:2017-09-09 00:04:57      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:bsp   col   tiny   contain   not   sum   empty   red   lists   

题目:You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

输入那里 为 342 + 564   输出为 807。

这题难度为中等难度,其实这题难度比较低,就用小学做加减法的思路做 ,同位相加,满10进1。

 1 package cn.tiny77.leetcodepart1;
 2 
 3 public class Solution1 {
 4 
 5     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
 6         int jinwei = 0;
 7         ListNode result = null;
 8         ListNode temp = null;
 9         while(l1!=null || l2!=null) {
10             int val =  (l1==null?0:l1.val) + (l2==null?0:l2.val) + jinwei;
11             jinwei = val > 9 ? 1: 0;
12             val %= 10;
13             if(result == null) {
14                 result = new ListNode(val);
15                 temp = result;
16             }else {
17                 temp.next = new ListNode(val);
18                 temp = temp.next;
19             }
20             if(l1!=null) l1 = l1.next;
21             if(l2!=null) l2 = l2.next;
22         }
23         if(jinwei!=0) {
24             temp.next = new ListNode(jinwei);26         }
27         return result;
28     }
29 
30 }

 

leetcode 002 两个数相加

标签:bsp   col   tiny   contain   not   sum   empty   red   lists   

原文地址:http://www.cnblogs.com/qins/p/7496401.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!