leetcode brush 31 title

Today's topic is the brush LeetCode second question, the two numbers together, and now to do this question is very simple

First thought was, right two numbers are extracted, and then added together, and then generate a new list, but that there is a problem, is likely to exceed the maximum number of data type int. code show as below:

public  static ListNode Solution (ListNode L1, L2 ListNode) {
         // this approach is not correct, because the input string may exceed the maximum range int 
        ListNode head = new new ListNode (0 ); 
        ListNode P = head; 
        the StringBuilder StringBuilder = new new the StringBuilder ();
         the while (L1 =! null ) { 
            StringBuilder.Insert ( 0 , l1.val); 
            L1 = l1.next; 
        } 
        the StringBuilder stringBuilder2 = new new the StringBuilder ();
         the while ! (L2 = null){
            stringBuilder2.insert(0,l2.val);
            l2=l2.next;
        }
        int sum=Integer.parseInt(stringBuilder.toString())+Integer.parseInt(stringBuilder2.toString());
        List<Integer> list=new ArrayList<>();
        while (sum!=0){
            list.add(sum%10);
            sum=sum/10;
        }
        for (int i = 0; i <list.size() ; i++) {
            ListNode listNode=new ListNode(list.get(i));
            p.next=listNode;
            p=listNode;
        }
        return head.next;
    }

Then, because the data is stored from low to high Well, therefore, the process can be simulated data are added, can be added up. At this time point to note is that the need for a global number, to ensure that the data needs to carry, and ultimately need to determine if all the numbers together, eventually carry, we also need to generate a new list node

public static ListNode solution2(ListNode l1,ListNode l2){
        ListNode head=new ListNode(0);
        ListNode p=head;
        int pre=0;
        while (l1!=null && l2!=null){
            int num1=l1.val;
            int num2=l2.val;
            l1=l1.next;
            l2=l2.next;
            int sum=num1+num2+pre;
            ListNode newnode=new ListNode(sum%10);
            pre=sum/10;
            p.next=newnode;
            p=newnode;
        }
        ListNode others=new ListNode(0);
        if (l1!=null){
            others.next=l1;
        }else if (l2!=null){
            others.next=l2;
        }
        others=others.next;
        while (others!=null){
            int num=others.val;
            int sum=num+pre;
            ListNode newnode=new ListNode(sum%10);
            pre=sum/10;
            p.next=newnode;
            p=newnode;
            others=others.next;
        }
        if (pre!=0){
            ListNode newnode=new ListNode(pre);
            p.next=newnode;
        }
        return head.next;
    }

 

Guess you like

Origin www.cnblogs.com/cquer-xjtuer-lys/p/11517012.html
Recommended