leetcode刷题31

今天刷的题是LeetCode第2题,两数相加,现在来做这个题还是很简单的

首先想到的是,吧两个数都提取出来,然后相加,再生成新的链表,但是这个有个问题,就是数据有可能超过int类型的最大数。代码如下:

public static ListNode solution(ListNode l1,ListNode l2){
        //这种做法是不正确的,因为输入的字符串有可能超过int的最大范围
        ListNode head=new ListNode(0);
        ListNode p=head;
        StringBuilder stringBuilder=new StringBuilder();
        while (l1!=null){
            stringBuilder.insert(0,l1.val);
            l1=l1.next;
        }
        StringBuilder stringBuilder2=new StringBuilder();
        while (l2!=null){
            stringBuilder2.insert(0,l2.val);
            l2=l2.next;
        }
        int sum=Integer.parseInt(stringBuilder.toString())+Integer.parseInt(stringBuilder2.toString());
        List<Integer> list=new ArrayList<>();
        while (sum!=0){
            list.add(sum%10);
            sum=sum/10;
        }
        for (int i = 0; i <list.size() ; i++) {
            ListNode listNode=new ListNode(list.get(i));
            p.next=listNode;
            p=listNode;
        }
        return head.next;
    }

然后,因为数据是从低位到高位存储的嘛,因此,可以模拟数据相加的过程,直接相加即可。这时候需要注意的一点就是,需要一个全局的数,来保证数据是否需要进位,并且最终需要进行判断,如果所有数相加,最终有进位,那么还需要生成新的链表节点

public static ListNode solution2(ListNode l1,ListNode l2){
        ListNode head=new ListNode(0);
        ListNode p=head;
        int pre=0;
        while (l1!=null && l2!=null){
            int num1=l1.val;
            int num2=l2.val;
            l1=l1.next;
            l2=l2.next;
            int sum=num1+num2+pre;
            ListNode newnode=new ListNode(sum%10);
            pre=sum/10;
            p.next=newnode;
            p=newnode;
        }
        ListNode others=new ListNode(0);
        if (l1!=null){
            others.next=l1;
        }else if (l2!=null){
            others.next=l2;
        }
        others=others.next;
        while (others!=null){
            int num=others.val;
            int sum=num+pre;
            ListNode newnode=new ListNode(sum%10);
            pre=sum/10;
            p.next=newnode;
            p=newnode;
            others=others.next;
        }
        if (pre!=0){
            ListNode newnode=new ListNode(pre);
            p.next=newnode;
        }
        return head.next;
    }

原文地址:https://www.cnblogs.com/cquer-xjtuer-lys/p/11517012.html

时间: 2024-10-01 01:05:41

leetcode刷题31的相关文章

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

【leetcode刷题笔记】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 题解: 思路比较简单,每条直线都可以表示为y=kx+b,所以对于任意三点,如果它们共线,那么它们中任意两点的斜率都相等. 所以就遍历points数组,对其中的每一个元素计算它和位于它后面的数组元素的斜率并保存在一个hashmap中. 这个hashmap的键就是两点构成直线的斜率,值就是和当前元素po

【leetcode刷题笔记】Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 题解:以前做过的Spiral Matrix是给一个矩阵螺旋式的输出,这道题是给一个n,螺旋式的

【leetcode刷题笔记】Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 题解:因为题目要求原地算法,所以我们只能利用矩阵第一行和第一列存放置零信息. 首先遍历第一行和第一列,看他们是否需要全部置零,用两个变量first_column_zero和first_row_zero来记录: 遍历矩阵,如果某个位置matrix[i][j]出现了0,就把matrix[i][0]和Matrix[0

【leetcode刷题笔记】Multiply Strings

Given two numbers represented as strings, return multiplication of the numbers as a string. Note: The numbers can be arbitrarily large and are non-negative. 题解:就是让实现一个大整数乘法. 假设两个数num1和num2的长度分别是len1和len2,那么最后得到的答案,在最高位有进位的时候,就是len1+len2位,否则是len1+len2

【leetcode刷题笔记】Substring with Concatenation of All Words

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. For example, given:S: "b

【leetcode刷题笔记】Sort List

Sort a linked list in O(n log n) time using constant space complexity. 题解:实现一个链表的归并排序即可.主要分为三部分: 1.找到中点并返回的函数findMiddle; 2.归并函数merge; 3.排序函数sortList. 数组的findMiddle函数非常容易实现,链表就有一点tricky了.首先设置两个指针,一个slow初始化为head,一个fast初始化为head.next,然后slow一次走一步,fast一次走两