首页 > 代码库 > [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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。