LeetCode 02 两个数字相加

小灰灰 2022-03-09 14:20 273阅读 0赞

2. Add Two Numbers 难度:Medium

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:

  1. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
  2. Output: 7 -> 0 -> 8
  3. Explanation: 342 + 465 = 807.

翻译:给出两个非空的链表代表两个非负的整数。数字以相反的顺序存储,每个节点包含一个数字,将两个数相加并把结果作为一 个链表返回。

本题最关键的地方在于解决进位问题。

  1. package pers.leetcode;
  2. /**
  3. * LeetCode 第二题 难易程度: Medium
  4. *
  5. * @author admin
  6. * @date 2019/3/11 17:03
  7. */
  8. /**
  9. * 单向链表节点
  10. */
  11. class ListNode{
  12. int val;
  13. ListNode next;
  14. ListNode(int x){
  15. val = x;
  16. }
  17. }
  18. public class AddTwoNumbers {
  19. public static void main(String[] args) {
  20. ListNode l1 = new ListNode(2);
  21. ListNode cur1 = l1;
  22. cur1.next = new ListNode(4);
  23. cur1 = cur1.next;
  24. cur1.next = new ListNode(3);
  25. ListNode l2 = new ListNode(5);
  26. ListNode cur2 = l2;
  27. cur2.next = new ListNode(6);
  28. cur2 = cur2.next;
  29. cur2.next = new ListNode(4);
  30. ListNode result = addTwoNumbers(l1, l2);
  31. while (result != null){
  32. System.out.println(result.val);
  33. result = result.next;
  34. }
  35. }
  36. /**
  37. * 尾插法 插入节点
  38. *
  39. * @param l1 第一个链表
  40. * @param l2 第二个链表
  41. * @return 结果链表
  42. */
  43. public static ListNode addTwoNumbers(ListNode l1, ListNode l2){
  44. ListNode dummyHead = new ListNode(0);
  45. ListNode curr = dummyHead;
  46. int carry = 0;
  47. while (l1 != null || l2 != null){
  48. int d1 = (l1 != null) ? l1.val : 0;
  49. int d2 = (l2 != null) ? l2.val : 0;
  50. int sum = d1 + d2 + carry;
  51. carry = sum / 10;
  52. curr.next = new ListNode(sum % 10);
  53. curr = curr.next;
  54. if (l1 != null){
  55. l1 = l1.next;
  56. }
  57. if (l2 != null){
  58. l2 = l2.next;
  59. }
  60. }
  61. if (carry == 1 ){
  62. curr.next = new ListNode(1);
  63. }
  64. return dummyHead.next;
  65. }
  66. }

carry 表示是否进位 ,初始值为 0 ,以后等于 sum/10 要么为0 要么为1,为1则表示下一位数字相加需要进位。

最后 ,假如最后两个链表的最后一位相加还要进位,那么就新构造一个 值为 1 的节点,加到当前结果链表的末尾即可。

发表评论

表情:
评论列表 (有 0 条评论,273人围观)

还没有评论,来说两句吧...

相关阅读

    相关 数字相加

    1.编程题目 题目:要实现两个百位长的数字直接相加 分析:因为数字太长所以无法直接相加,所以采用按位相加,然后组装的方式。(注意进位) 2.编程实现