美文网首页码农的世界leetcode刷题
leetcode-不同类型的数相加

leetcode-不同类型的数相加

作者: Upstreamzy | 来源:发表于2019-03-17 17:03 被阅读0次

    好吧到今天开始我就完成了leetcode第二个主题,每天一道编程题必须要坚持下去,这次我做的题大多是让两个东西相加,这个东西可以是两个整型字符串、二进制字符串、整型链表等等。
    我个人觉得这道题的灵感主要是来自《数字逻辑》里面的全加器,这个全加器大约是这个样子的


    330px-1-bit_full-adder.svg.png

    A和B是两个本位数Cin是来自低位的进位,S是面向高位的进位,基本上依靠这个就能把这类题的最主要的大体循环结构搞出来了:
    示例代码

    //假设传入的参数是两个整型字符串num1和num2
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; ) {
                int sum = carry;
                if (i >= 0) sum += num1.charAt(i--) - '0';
                if (j >= 0) sum += num2.charAt(j--) - '0';
                stringBuilder.append(sum % 10);
                carry = sum / 10;
            }
    

    来道例题:

    1. Add Two Numbers
      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:

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8
    Explanation: 342 + 465 = 807.
    然后我的解题方法是:

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            int carry = 0;
            ListNode corrent = new ListNode(-20);
            ListNode result = corrent;
            for (ListNode list1 = l1, list2 = l2; list1 != null || list2 != null || carry > 0; ) {
                int sum = carry;
                if (list1 != null) {
                    sum += list1.val;
                    list1 = list1.next;
                }
                if (list2 != null) {
                    sum += list2.val;
                    list2 = list2.next;
                }
    
                corrent.next = new ListNode(sum % 10);
                corrent = corrent.next;
                carry = sum / 10;
            }
            
            return result.next;
        }
    

    emmm最后的运行情况:


    image.png

    类似的题还有这些:


    image.png

    相关文章

      网友评论

        本文标题:leetcode-不同类型的数相加

        本文链接:https://www.haomeiwen.com/subject/ispumqtx.html