首页 > 代码库 > [LeetCode] - Add Two Numbers

[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