每天一道算法题系列:
来源:力扣(LeetCode)
本题链接:https://leetcode-cn.com/problems/add-two-numbers/submissions/
来源是力扣,大家喜欢可以去力扣中文网做相应的其他的题,某浏览器直接搜力扣即可。
因为这次的题目是单链表相关的知识,如果对链表知识比较薄弱的,可以看这篇文章,简单介绍了单链表的新增和删除。
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
/***
* 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序
* 的方式存储的,并且它们的每个节点只能存储 一位 数字。
*
* 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
*
* 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
*
* 示例:
*
* 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
* 输出:7 -> 0 -> 8
* 原因:342 + 465 = 807
*
*/
public class AddTwoNumbers {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pre = new ListNode(0);
ListNode cur = pre;
int carry = 0 ;
while(l1 != null || l2 != null ){
int x = l1 == null ? 0 : l1.val ;
int y = l2 == null ? 0 : l2.val ;
/*
这里是每次取前面两个值,然后进行加减,如果x+y大于10 那么就需要进位,
那么进位是如何加到第二次上面的话,就定义了一个carry来表示
这里(x + y + carry)-10 = (x + y + carry)%10了
*/
int sum = x + y + carry > 9 ? (x + y + carry)-10: x + y + carry ;
cur.next = new ListNode(sum);
carry = (x+y+ carry )>9 ? 1 : 0 ;
//因为上面已经加了一次了,所以在这里必须到下一个节点
cur = cur.next;
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
/*
这里主要是判断99 + 10 这种,两位数的加法变成3位数的情况
如果不做这一步的话,99 + 99 就会变成89 而不是198
如果2个两位数加起来还是2位数的话 这里是不会大于9的*/
if(((x+y+ carry )>9 ? 1 : 0) == 1) {
cur.next = new ListNode(carry);
}
}
return pre.next;
// return 1;
}
public static void main(String[] args) {
int[] input=new int[]{8,3,2};
int[] input1=new int[]{9,2,1};
//这个方法是加节点的方法
ListNode listNode=buildListNode(input);
ListNode listNode1=buildListNode(input1);
addTwoNumbers(listNode,listNode1);
}
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
private static ListNode buildListNode(int[] input){
ListNode first = null,last = null,newNode;
int num;
if(input.length>0){
for(int i=0;i<input.length;i++){
newNode=new ListNode(input[i]);
newNode.next=null;
if(first==null){
first=newNode;
last=newNode;
}
else{
last.next=newNode;
last=newNode;
}
}
}
return first;
}
}
如果本篇内容有问题,请第一时间联系我,我会第一时间修改。
谢谢大家。
昨天的题:每天一道算法题系列一之两数之和
本文参考链接:https://blog.csdn.net/jpp_aaa/article/details/79455485