[LeetCode] - Add Two Numbers

Posted seako

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] - Add Two Numbers相关的知识,希望对你有一定的参考价值。

題目連結

Problem.

 

就是用link list(鏈表)反向表達兩個正整數,執行相加

342 + 465 就變成題目範例那樣反自表達成 2 4 3 跟 5 6 4

 

solution.(以單向鏈表)

public class Program {
        public static void Main(string[] args) {
            ListNode l1 = new ListNode(1);
            l1.next = new ListNode(2);

            ListNode l2 = new ListNode(9);
            l2.next = new ListNode(8);

            ListNode rs = AddTwoNumbers(l1, l2);

            Console.ReadKey();
        }

        public static ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
            ListNode node1 = l1;
            ListNode node2 = l2;
            int sum;
            ListNode retur = new ListNode(0);
            //關鍵這行,讓tmp & retur 指到同樣的地方,然後只更新tmp
            ListNode tmp = retur;
            int add;
            int remain;
            while(node1 != null || node2 != null) {
                //要取值運算,null的就先給預設值
                node1 = node1 ?? new ListNode(0);
                node2 = node2 ?? new ListNode(0);
                sum = node1.val + node2.val;

                add = sum / 10;
                remain = sum % 10;
                //取出next值做下一輪運算
                node1 = node1.next;
                node2 = node2.next;
                //進位
                if(add > 0) {
                    node1 = node1 ?? new ListNode(0);
                    node2 = node2 ?? new ListNode(0);

                    node1.val += add;
                }
                
                tmp.next = new ListNode(remain);
                tmp = tmp.next;
            }

            return retur.next;
        }
    }

    public class ListNode {
        public int val;
        public ListNode next;
        public ListNode(int x) {
            val = x;
        }
    }

 

流程圖

 

 參考看看

 

以上是关于[LeetCode] - Add Two Numbers的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 2. Add Two Numbers

[Leetcode Week15]Add Two Numbers

LeetCode - 2 - Add Two Numbers

[LeetCode] Add Two Numbers

[LeetCode] Add Two Numbers

LeetCode|Add Two Numbers