• 2. Add Two Numbers


    /**
     * 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结果的方法会造成溢出的错误
            int isOver=0;
            ListNode t1=l1;
            ListNode t2=l2;
            ListNode head=null;
            ListNode last=null;
            while(t1!=null&&t2!=null)
            {
                int temp=t1.val+t2.val+isOver;
                if(temp>=10)
                    isOver=1;
                else
                    isOver=0;
                ListNode t=new ListNode(temp%10);
                if(head==null)
                    head=t;
                if(last!=null)
                    last.next=t;
                last=t;
                t1=t1.next;
                t2=t2.next;
            }
            while(t1!=null)
            {
                int temp=t1.val+isOver;
                if(temp>=10)
                    isOver=1;
                else
                    isOver=0;
                ListNode t=new ListNode(temp%10);
                if(head==null)
                    head=t;
                if(last!=null)
                    last.next=t;
                last=t;
                t1=t1.next;
            }
            while(t2!=null)
            {
                int temp=t2.val+isOver;
                if(temp>=10)
                    isOver=1;
                else
                    isOver=0;
                ListNode t=new ListNode(temp%10);
                if(head==null)
                    head=t;
                if(last!=null)
                    last.next=t;
                last=t;
                t2=t2.next;
            }
            if(t1==null&&t2==null&&isOver==1)
            {
                ListNode t=new ListNode(1);
                if(head==null)
                    head=t;
                if(last!=null)
                    last.next=t;
                last=t;
            }
            return head;
        }
    }
  • 相关阅读:
    ubuntu安装RabbitMQ
    pycharm中引入相对路径错误
    python之pip
    ubuntu安装django
    ubuntu16安装python3.7
    ubuntu上用源码进行一键安装mysql
    tar命令
    linux之bc命令
    linux源码安装
    ubuntu安装搜狗输入法后无法使用goland的快捷键 ctrl+alt+B
  • 原文地址:https://www.cnblogs.com/aguai1992/p/5754331.html
Copyright © 2020-2023  润新知