美文网首页
Add Two Numbers

Add Two Numbers

作者: sunner168 | 来源:发表于2017-06-24 11:00 被阅读10次

题目

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

作答

java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int up = 0 ,sum = 0 ;
        ListNode node=null, start=null; 
        do{
         if(l1!=null&&l2!=null){
          sum = l1.val + l2.val+up;
          up = 0;
          if(sum>=10){
              up = 1;
              sum = sum % 10 ;
          }
          if(node==null){
              node = new ListNode(sum);
              start = node ;
          }else{
              node.next = new ListNode(sum);
              node = node.next;
          }
         }
          
          l1 = l1 !=null? l1.next:null;
          l2 = l2 !=null? l2.next:null;
          //判断位数不一样的情况
          if(l1==null&&l2!=null){
              sum = l2.val+up;
              up = 0;
              if(sum>=10){
              up = 1;
              sum = sum % 10 ;
              }
               node.next = new ListNode(sum);
               node = node.next;
          }
          if(l2==null&&l1!=null){
              sum = l1.val+up;
              up = 0;
              if(sum>=10){
              up = 1;
              sum = sum % 10 ;
              }
               node.next = new ListNode(sum);
               node = node.next;
               
          }
        }while(l1!=null||l2!=null);
         //处理为完成的部分
         if(up==1){
             node.next = new ListNode(1);
         }
        return start;
    }
   
}

相关文章

网友评论

      本文标题:Add Two Numbers

      本文链接:https://www.haomeiwen.com/subject/lmxkcxtx.html