• Leetcode Add Two Numbers


    You are given two linked lists representing two non-negative numbers. 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.

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8


    解题思路:

    本题解题思路与Add Binary一模一样,都是按位加,用flag记是否有进位,有是1,没有是0,不同的地方就是LinkedList的操作和String有一些区别,这点要特别注意!!当然我看到一个答案用的变量比我少,感觉更漂亮,也贴上来。

    Add Binary   


     Java code

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode result = new ListNode(0);
            ListNode p = result;
            ListNode p1 = l1, p2 = l2;
           
            int flag = 0;
            while(p1 != null || p2 != null){
                int v1 = 0, v2 = 0;
                if(p1 != null){
                    v1 = p1.val;
                    p1 = p1.next;
                }
                if(p2 != null){
                    v2 = p2.val;
                    p2 = p2.next;
                }
                int sum = v1+v2+flag;
                if(sum >= 10){
                    p.next = new ListNode(sum -10);
                    flag = 1;
                }else {
                    p.next = new ListNode(sum);
                    flag = 0;
                }
                p = p.next;
            }
            if(flag == 1){
                p.next = new ListNode(1);
            }
            return result.next;
        }
    }

    或者

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            int carry = 0;
            ListNode result = new ListNode(0);
            ListNode p1 = l1, p2 = l2, p3 = result;
            while(p1 != null || p2 != null){
                if(p1 != null){
                    carry += p1.val;
                    p1 = p1.next;
                }
                if(p2 != null){
                    carry += p2.val;
                    p2 = p2.next;
                }
                p3.next = new ListNode(carry%10);
                p3 = p3.next;
                carry /= 10;
            }
            if(carry == 1){
                p3.next = new ListNode(1);
            }
            return result.next;
        }

    Reference:

    1. http://www.programcreek.com/2012/12/add-two-numbers/

     

  • 相关阅读:
    Leetcode424. 替换后的最长重复字符
    Leetcode82. 删除排序链表中的重复元素 II
    python 无序模块,hashlib模块
    python 内置方法
    python 面向对象的三大特性
    python 面向对象
    python 递归函数和二分查找
    python 装饰器
    python 函数名,闭包
    python 函数进阶
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4827837.html
Copyright © 2020-2023  润新知