Add Two Numbers

題目
You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Explanation: 342 + 465 = 807.

答案

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l3 = new ListNode(0);
        ListNode ret = l3;
        int sum, num, carry = 0;
        while(l1 != null || l2 != null) {
            sum = ((l1 != null)?l1.val:0) + ((l2 != null)?l2.val:0) + carry;
            num = sum % 10;
            carry = (sum >= 10)? 1:0;
            
            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;
            
            l3.val = num;
            if(l1 != null || l2 != null)
                l3.next = new ListNode(0);
            else
                if(carry != 0) l3.next = new ListNode(1);
            l3 = l3.next;
        }
        return ret;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 上通信的課就跟室友一起刷題玩,結(jié)果讀題目讀了半天,好歹我也是過了四級的人啊,怎么能這樣,干脆百度題目意思…… 題目...
    做夢枯島醒閱讀 290評論 0 0
  • 題目: You are given two non-empty linked lists representing...
    要上班的斌哥閱讀 234評論 0 0
  • Description You are given two non-empty linked lists repr...
    CNSumi閱讀 284評論 0 0
  • You are given two non-empty linked lists representing two...
    飛飛廉閱讀 154評論 0 0
  • 昨天剛給某人發(fā)的微信:我們怎么變成了這樣。半夜就做夢了,只覺得自己一直在流眼淚,后來高澍跟我講,你昨天講夢話了,你...
    思焱閱讀 174評論 0 0

友情鏈接更多精彩內(nèi)容