• 题目:

两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

  • 示例:
 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
  • 代码实现:
public class AddTwoNumbers {
/**
* 思路:实现链表与long数值的互转
* 失败:链表结构太长超过long值无法转换
* @param l1 ListNode
* @param l2 ListNode
* @return ListNode
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
long m = 0, mIndex = 0;
long n = 0, nIndex = 0; while(true) {
Double d = Math.pow(10, mIndex);
m += l1.val * d.longValue();
if(l1.next != null) {
l1 = l1.next;
mIndex++;
} else {
break;
}
} while(true) {
Double d = Math.pow(10, nIndex);
n += l2.val * d.longValue();
if(l2.next != null) {
l2 = l2.next;
nIndex++;
} else {
break;
}
} return ListNode.buildFromNumber(m + n);
} /**
* 思路:每一个节点进行相加,如果有进位,则给下一节点额外加1
* @param l1 ListNode
* @param l2 ListNode
*/
public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
ListNode p1 = l1;
ListNode p2 = l2;
ListNode head = new ListNode(0);
ListNode curr = head;
int bit = 0;
while(p1 != null || p2 != null) {
int x = p1 == null ? 0 : p1.val;
int y = p2 == null ? 0 : p2.val;
int sum = x + y + bit;
if (sum >= 10) {
sum = sum % 10;
bit = 1;
} else {
bit = 0;
} curr.next = new ListNode(sum);
curr = curr.next; p1 = p1 == null ? null : p1.next;
p2 = p2 == null ? null : p2.next;
} if(bit > 0) {
curr.next = new ListNode(bit);
} return head.next;
} public static void main(String[] args) {
int[] n1 = {9};
int[] n2 = {1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9}; ListNode l1 = ListNode.buildFromArray(n1);
ListNode l2 = ListNode.buildFromArray(n2); System.out.println(l1.dump());
System.out.println(l2.dump()); AddTwoNumbers addTwoNumbers = new AddTwoNumbers();
ListNode l3 = addTwoNumbers.addTwoNumbers2(l1, l2); System.out.println(l3.dump());
} public static void main2(String[] args) {
long n1 = 9L;
long n2 = 999999999999999991L; ListNode l1 = ListNode.buildFromNumber(n1);
ListNode l2 = ListNode.buildFromNumber(n2); System.out.println(l1.dump());
System.out.println(l2.dump()); AddTwoNumbers addTwoNumbers = new AddTwoNumbers();
ListNode l3 = addTwoNumbers.addTwoNumbers(l1, l2); System.out.println(l3.dump());
}
} public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; } public String dump() {
StringBuilder out = new StringBuilder();
out.append(val); ListNode nextNode = this.next;
while(nextNode != null) {
out.append(" -> ").append(nextNode.val);
nextNode = nextNode.next;
} return out.toString();
} public static ListNode buildFromArray(int[] arr) {
ListNode head = new ListNode(0);
ListNode curr = head;
for (int a : arr) {
curr.next = new ListNode(a);
curr = curr.next;
} return head.next;
} public static ListNode buildFromNumber(long num) {
ListNode head = new ListNode(0);
ListNode curr = head;
int sumIndex = 1;
while(true) {
Double d = Math.pow(10, sumIndex);
long bitVal = num % d.longValue();
long val = bitVal / (d.longValue() / 10); curr.next = new ListNode((int)val);
curr = curr.next; sumIndex++;
num -= bitVal;
if (num <= 0) {
break;
}
} return head.next;
}
}

leetcode实践:通过链表存储两数之和的更多相关文章

  1. LeetCode(1): 两数之和

    本内容为LeetCode第一道题目:两数之和 # -*- coding: utf-8 -*- """ Created on Sun Mar 10 19:57:18 201 ...

  2. Leetcode之二分法专题-167. 两数之和 II - 输入有序数组(Two Sum II - Input array is sorted)

    Leetcode之二分法专题-167. 两数之和 II - 输入有序数组(Two Sum II - Input array is sorted) 给定一个已按照升序排列 的有序数组,找到两个数使得它们 ...

  3. Leetcode#1.Two Sum(两数之和)

    题目描述 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 15], ta ...

  4. 【LeetCode】1. Two Sum 两数之和

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:two sum, 两数之和,题解,leetcode, 力 ...

  5. leetcode题库练习_两数之和

    题目:两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,数组中同一个元素不能 ...

  6. [LeetCode] Sum of Two Integers 两数之和

    Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Exam ...

  7. LeetCode每天一题之两数之和

    这个LeetCode刷题系列的博客权当是为自己记一下笔记吧.博客系列会从LeetCode的第一题开始刷,同时会从零开始学习[因为我就是零/(ㄒoㄒ)/~~].同时,如果有写错的地方,希望大佬们在评论区 ...

  8. leetcode刷题笔记-1. 两数之和(java实现)

    题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,数组中同一个元素不能使 ...

  9. LeetCode 1. Two Sum (两数之和)

    Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...

随机推荐

  1. Asp .Net core 2 学习笔记(1) —— Starup

    这个系列的初衷是便于自己总结与回顾,把笔记本上面的东西转移到这里,态度不由得谨慎许多,下面是我参考的资源: ASP.NET Core 中文文档目录 官方文档 记在这里的东西我会不断的完善丰满,对于文章 ...

  2. ModelValidator基于元数据的验证

    ModelValidator主要是应用在ModelMetadata元数据的类型上或类型属性上.它是验证的基础类型,所有的ModelValidatorProviders.DataAnnotationVa ...

  3. 浏览器环境下JavaScript脚本加载与执行探析之代码执行顺序

    本文主要基于向HTML页面引入JavaScript的几种方式,分析HTML中JavaScript脚本的执行顺序问题 1. 关于JavaScript脚本执行的阻塞性 JavaScript在浏览器中被解析 ...

  4. 如何做好错误处理?(PHP篇)

    起因 之前我在封装 PHP 一个类库的时候,如果有遇到错误(例如构造函数传参不合法的话),则直接 die() ,后来发现这种方法很不好,会直接退出程序. 所以我想到给 PHP 上异常捕获的机制了. 错 ...

  5. 移动一根火柴使等式成立js版本

    <html><head><meta http-equiv="Content-Type" content="text/html; charse ...

  6. requests请求例子

    实例一: class GetSalerInfo(View): def post(self, request): userid = request.POST/GET.get('userid',None) ...

  7. Python code 提取UML

    Python是一门支持面向对象编程的语言,在大型软件项目中,我们往往会使用面向对象的特性去组织我们的代码,那有没有这样一种工具,可以帮助我们从已有代码中提取出UML图呢?答案是有的.以下,我们逐个介绍 ...

  8. 如何开启windows的linux子系统

    win10一周年纪念版  1607的版本增加了bash,bash,bash,windows的shell中可以直接运行bash了. 下面说一下配置步骤: 1.设置 —更新和安全—针对开发人员,选择开发人 ...

  9. JSONP是什么

    摘自:https://segmentfault.com/a/1190000007935557 一.JSONP的诞生 首先,因为ajax无法跨域,然后开发者就有所思考 其次,开发者发现, <scr ...

  10. android studio 查看包有没有重复引用

    在windows下studio内的命令行里面     gradlew :app:dependencies 苹果系统  ./gradlew :app:dependencies