C# 152ms Solution with Explanation


  • 1

    When we're doing an addition, what we need to notice is only the 9, which may become 10. However, it only happens when the addition is exactly 9, so we just need to consider 3 conditions: >9, =9, and<9.

    Assuming that the current result is 3→9→9.
    If the next number is less then 9, then the current part won't change at all, so just skip the node to the next digits.
    If it's exactly 9, then let the node stay and make it 3→9→9→9.
    If it's more than 9, for example, 15, then the result would become 4→0→0→5. Now the 4→0→0 part won't be changed any more, so move the node to 5 and continue the next calculation.

    Following is my solution:

    public class Solution {
        public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
            ListNode i1 = l1, i2 = l2;
            int n1=0, n2=0;
            while(i1!=null){n1++;i1=i1.next;}i1=l1;
            while(i2!=null){n2++;i2=i2.next;}i2=l2;
            
            ListNode ans = new ListNode(0), wait9 = ana, go = ans;
            if(n1>n2)for(int i=n1-n2; i>0; i--){
                go.next=new ListNode(i1.val);
                go=go.next;
                if(go.val<9)wait9=go;
                i1=i1.next;
            }
            else if(n2>n1)for(int i=n2-n1; i>0; i--){
                go.next=new ListNode(i2.val);
                go=go.next;
                if(go.val<9)wait9=go;
                i2=i2.next;
            }
            
            for(;i1!=null;i1=i1.next, i2=i2.next){
                go.next=new ListNode(i1.val+i2.val);
                go=go.next;
                if(go.val>9){
                    wait9.val++;
                    wait9=wait9.next;
                    while(wait9!=go){
                        wait9.val=0;
                        wait9=wait9.next;
                    }
                    go.val-=10;
                }
                else if(go.val<9)wait9=go;
            }
            
            return (ans.val==0)?ans.next:ans;
        }
    }
    

    I think it's a little too long, so I wonder how I can write it better.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.