LeetCode - Add Two Numbers

来源:互联网 发布:svd推荐算法 编辑:程序博客网 时间:2024/05/29 08:47

问题链接:https://oj.leetcode.com/problems/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


问题API:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */


public ListNode addTwoNumbers(ListNode l1, ListNode l2)


分析:这题其实很简单,不知道为什么leetcode给的medium的难度。就是逐步往下加然后保留进位即可。代码如下:

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        if(l1 == null || l2 == null)            return l1 == null ? l2 : l1;        ListNode tmp1 = l1, tmp2 = l2;        int next = 0, curbit = 0;        ListNode res = new ListNode(0);        ListNode tmp = res;        while(tmp1 != null || tmp2 != null || next != 0){            curbit = (tmp1 != null ? tmp1.val : 0) +  (tmp2 != null ? tmp2.val : 0) + next;            next = curbit / 10;            tmp.val = curbit % 10;            if(tmp1 != null)                tmp1 = tmp1.next;            if(tmp2 != null)                tmp2 = tmp2.next;            if(tmp1 != null || tmp2 != null || next != 0){                tmp.next = new ListNode(0);                tmp = tmp.next;            }        }        return res;    }

这题其实有一个变种,难度骤然提升很多。


这题里面链表是按照个十百位逐步往下连接,如果链表的连接方式是按照正常从高往低

也就是 1 - > 2 - > 3表示的不是321而是123。用O(n)的方式做加法。

分析和代码随后放上。

0 0
原创粉丝点击