zoukankan      html  css  js  c++  java
  • leetcode:Add Two Numbers

    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

    解决方法(java版)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
     
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            List<ListNode> list=new LinkedList<ListNode>();
            int valuenext=0;
            while(l1!=null&&l2!=null){
             int value=(valuenext+l1.val+l2.val)%10;
             //valuenext=0;
             valuenext=(l1.val+l2.val+valuenext)/10;
             list.add(new ListNode(value));
             l1=l1.next;
             l2=l2.next;
            }
             if(l1==null&&l2!=null){
             while(l2!=null){
                 int value=(valuenext+l2.val)%10;
                 valuenext=(l2.val+valuenext)/10;
                 list.add(new ListNode(value));
              l2=l2.next;
             }
            }
            else if(l2==null&&l1!=null){
             while(l1!=null){
                 int value=(valuenext+l1.val)%10;
                 valuenext=(l1.val+valuenext)/10;
                 list.add(new ListNode(value));
              l1=l1.next;
             }      
            }
            if(valuenext!=0&&l1==null&&l2==null){
              list.add(new ListNode(valuenext));
             }
            for(int i=0;i<list.size()-1;i++){
              list.get(i).next=list.get(i+1);
            }
            return list.get(0);
        }
    }

  • 相关阅读:
    第二天第三课:03-reques_header_two
    第二天第二节:02-request_header
    爬虫第二天第一课:01-get_params2
    爬虫第三天第二课:02-auth-use用户密码认证
    爬虫第三天:01-money-proxy-handler代理池
    设计模式(C#)——07装饰者模式
    设计模式(C#)——06桥接模式
    设计模式(C#)——05适配器模式
    设计模式(C#)——04原型模式
    设计模式(C#)——03建造者模式
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/3349778.html
Copyright © 2011-2022 走看看