LeetCode 2 两数相加(链表)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 2 两数相加(链表)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目要求:
給定兩個非空鏈表來表示兩個非負整數。位數按照逆序方式存儲,它們的每個節點只存儲單個數字。將兩數相加返回一個新的鏈表。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 輸出:7 -> 0 -> 8 原因:342 + 465 = 807?
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/ class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {int total = l1.val + l2.val;ListNode res = new ListNode(total%10);int digit = total/10;// 判斷下一個位置有沒有值, 判斷有沒有進位digit為0,表示沒有進位.if(null != l1.next || null != l2.next || digit != 0){l1 = l1.next != null ? l1.next : new ListNode(0); l2 = l2.next != null ? l2.next : new ListNode(0);l1.val += digit; // 加上進位res.next = addTwoNumbers(l1, l2);}return res;} }?
總結
以上是生活随笔為你收集整理的LeetCode 2 两数相加(链表)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 1: 找出两个数相加等
- 下一篇: 《深入理解计算机系统》读书笔记八:程序结