Leetcode-445. Add Two Numbers II

来源:互联网 发布:网络高清摄像机哪家好 编辑:程序博客网 时间:2024/06/05 19:11

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 8 -> 0 -> 7
这个题目一开始想的挺简单的,考虑的是非负整数,所以先转换为整数然后相加,然后再转换成linkedList,但是没想到会溢出,所以干脆转换为字符串,然后做字符串加法,时间复杂度O(m+n)。Your runtime beats 74.72% of java submissions.

/** * 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) {        String number1 = getNumber(l1);        String number2 = getNumber(l2);        int i = number1.length() - 1;        int j = number2.length() - 1;        boolean support = false;        ListNode node = null;        while(i >= 0 && j >= 0){            int result = (number1.charAt(i) - '0') + (number2.charAt(j) - '0');            if(support) {result += 1; support = false;}            if(result >= 10) {support = true;result %= 10;}            ListNode temp = node;            node = new ListNode(result);            node.next = temp;            i--;j--;        }        while(i >= 0){            ListNode temp = node;            int result = (number1.charAt(i) - '0');            if(support) {result += 1; support = false;}            if(result >= 10) {support = true;result %= 10;}            node = new ListNode(result);            node.next = temp;            i--;        }        while(j >= 0){            ListNode temp = node;            int result = (number2.charAt(j) - '0');            if(support) {result += 1; support = false;}            if(result >= 10) {support = true;result %= 10;}            node = new ListNode(result);            node.next = temp;            j--;        }                if(support) {            ListNode temp = node;            node = new ListNode(1);            node.next = temp;        }                return node;    }        private String getNumber(ListNode node){        StringBuffer sb = new StringBuffer("");        while(node != null){            sb.append(node.val);            node = node.next;        }        return sb.toString();    }}





0 0
原创粉丝点击