2. Add Two Numbers (两数求和)

布满荆棘的人生 2022-06-12 02:15 210阅读 0赞

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

题目大意:两个非负数分别逆序存放在两个单链表中,将两个单链表代表的数求和,并将和以单链表的形式返回。

解题思路:双指针,先遍历完较短的链表,将两个链表对应节点值求和之后的值更新到较长的链表中,较短的链表遍历完后再接着遍历较长链表剩下的部分,此时仅以较长链表中节点的值作为求和加数,但是要注意处理有进位的情况。

源代码:(57 ms,beats 47.31%)

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  11. int lenth1 = 0, lenth2 = 0;
  12. ListNode p = l1, q = l2, result;
  13. int curRes;
  14. // 进位
  15. int carry = 0;
  16. while (p != null) {
  17. lenth1++;
  18. p = p.next;
  19. }
  20. while (q != null) {
  21. lenth2++;
  22. q = q.next;
  23. }
  24. if (lenth1 < lenth2) {
  25. result = l2;
  26. p = l1;
  27. q = l2;
  28. } else {
  29. result = l1;
  30. p = l2;
  31. q = l1;
  32. }
  33. ListNode preq = null;
  34. while (p != null) {
  35. curRes = p.val + q.val + carry;
  36. if (curRes >= 10) {
  37. carry = 1;
  38. curRes = curRes % 10;
  39. } else {
  40. carry = 0;
  41. }
  42. q.val = curRes;
  43. preq = q;
  44. p = p.next;
  45. q = q.next;
  46. }
  47. while (q != null) {
  48. curRes = q.val + carry;
  49. if (curRes >= 10) {
  50. carry = 1;
  51. curRes = curRes % 10;
  52. } else {
  53. carry = 0;
  54. }
  55. q.val = curRes;
  56. preq = q;
  57. q = q.next;
  58. }
  59. if (carry == 1) {
  60. preq.next = new ListNode(1);
  61. }
  62. return result;
  63. }
  64. }

发表评论

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

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

相关阅读

    相关 2.相加 Add Two Numbers

    题目描述 给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。如果,我们将这两个数相加起来,则会返回