首页 技术 正文
技术 2022年11月7日
0 收藏 384 点赞 589 浏览 1371 个字

Add Two Numbers

  • Total Accepted: 160702
  • Total Submissions: 664770
  • Difficulty: Medium

  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

  本题的思路其实很简单,两个链表的结构都是从低位到高位的顺序,税后要求返回的链表也是这样的结构。所以我们只需要依次循环两个链表,将对应位的数相加,并判断是否有进位,有进位则将进位累加到下一位即可。

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Num2 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null){
return l2 ;
}
if(l2 == null){
return l1 ;
}
int nextBit = (l1.val + l2.val)/10 ;
int curBit = (l1.val + l2.val)%10 ;
ListNode head = new ListNode(curBit) ;
ListNode temp = head ;
l1 = l1.next ;
l2 = l2.next ;
//当l1、l2对应位均存在时,进行计算
while(l1 != null && l2 != null){
curBit = (l1.val + l2.val + nextBit) % 10 ;
nextBit = (l1.val + l2.val + nextBit)/10 ;
ListNode node = new ListNode(curBit) ;
temp.next = node ;
temp = temp.next ;
l1 = l1.next ;
l2 = l2.next ;
}
//判断l1是否结束,没有结束继续
while(l1 != null){
curBit = (l1.val + nextBit) % 10 ;
nextBit = (l1.val + nextBit)/10 ;
ListNode node = new ListNode(curBit) ;
temp.next = node ;
temp = temp.next ;
l1 = l1.next ;
}
//判断l2是否结束,没有结束继续
while(l2 != null){
curBit = (l2.val + nextBit) % 10 ;
nextBit = (l2.val + nextBit)/10 ;
ListNode node = new ListNode(curBit) ;
temp.next = node ;
temp = temp.next ;
l2 = l2.next ;
}
//判断最后的进位位是否为0 ,不为0则需要保存下一位
if(nextBit != 0){
ListNode node = new ListNode(nextBit) ;
temp.next = node ;
}
return head ;
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,486
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,126
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289