zoukankan      html  css  js  c++  java
  • NO.2 Add Two Numbers

    使用递归算法

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            return add(l1, l2, 0);
        }
       public ListNode add(ListNode l1,ListNode l2,int carry)
         {
              if(l1==null && l2==null){
                    return carry == 0? null : new ListNode(carry);
                }
                if(l1==null && l2!=null){
                    l1 = new ListNode(0);
                }
                if(l2==null && l1!=null){
                    l2 = new ListNode(0);
                }
                int sum = l1.val + l2.val + carry;
                ListNode curr = new ListNode(sum % 10);
                curr.next = add(l1.next, l2.next, sum / 10);
                return curr;
         }
    }

    偷懒相加法,超过long的范围会失败

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if(l1==null&&l2==null){
                 return null;
             }
             //链表转long型
             long num1 = listToLong(l1);
             long num2 = listToLong(l2);
             return longToList(num1+num2);
        }
       //链表转数据
        public Long listToLong(ListNode l)
        {
            long num=0;
            long curr=1;
            int i=0;
            while(l!=null)
            {
                num=num+l.val*curr;
                curr=curr*10;
                l=l.next;
            }
            return num;
        }
        
        //数据转链表
        public ListNode longToList(Long num){       
            ListNode l3 = new ListNode(-1);
            l3.next = null;
            ListNode c = l3;
            c.val=(int)(num%10);
            num = num/10;
            while(num>0){       
                ListNode cnext = new ListNode((int)(num%10));
                cnext.next=null;
                c.next=cnext;
                num = num/10;
                c=c.next;
            }
            return l3;
        }
    }
  • 相关阅读:
    Ftp、Ftps与Sftp之间的区别
    Previous Workflow Versions in Nintex Workflow
    Span<T>
    .NET Core 2.0及.NET Standard 2.0 Description
    Announcing Windows Template Studio in UWP
    安装.Net Standard 2.0, Impressive
    SQL 给视图赋权限
    Visual Studio for Mac中的ASP.NET Core
    How the Microsoft Bot Framework Changed Where My Friends and I Eat: Part 1
    用于Azure功能的Visual Studio 2017工具
  • 原文地址:https://www.cnblogs.com/Maskisland/p/10020568.html
Copyright © 2011-2022 走看看