Add Two Numbers (leetcode2)
来源:互联网 发布:百度贴吧和天涯知乎 编辑:程序博客网 时间:2024/06/09 18:19
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
基本思路:首先想到将逆序存储的链结点转换为正确的整数,然后相加得到结果,再逆序存储回链表中去,因为考虑到数值非常的大,所以要使用到大数类,做出来的效率也比较慢,代码如下:
import java.math.BigInteger;class ListNode { int val; ListNode next; ListNode(int x) { val = x; } public String toString(){ return val+""; }}public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { BigInteger sum1 = BigInteger.ZERO; BigInteger sum2 = BigInteger.ZERO; ListNode current = l1; int power = 0; //转换成整数1 while(current!=null){ sum1 = sum1.add(new BigInteger(current.val+"").multiply(new BigInteger("10").pow(power++))); current = current.next; } current = l2; power = 0; //转换成整数2 while(current!=null){ sum2 = sum2.add(new BigInteger(current.val+"").multiply(new BigInteger("10").pow(power++))); current = current.next; } //得到答案整数 BigInteger sum = sum1.add(sum2); String str = sum.toString(); //存储回链表中 ListNode answer = new ListNode(Integer.valueOf(str.charAt(str.length()-1)+"")); current = answer; for(int i=str.length()-2;i>=0;i--){ current.next = new ListNode(Integer.valueOf(str.charAt(i)+"")); current = current.next; } return answer; }}
参考了discuss,得到了一个新的思路,就是每次对两个链表的一位数字(即一个链结点)进行相加,再考虑到是否需要进位的情况,就能很容易得到答案,代码如下:
public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int sum = 0; ListNode answer = new ListNode(0); ListNode current = answer; while (l1 != null || l2 != null || sum != 0) { if (l1 != null) { sum += l1.val; l1 = l1.next; } if (l2 != null) { sum += l2.val; l2 = l2.next; } current.next = new ListNode(sum%10); sum /= 10; current = answer.next; } return answer.next; }}
阅读全文
1 0
- [LeetCode2]Add Two Numbers
- leetcode2 add two numbers
- LeetCode2 Add Two Numbers
- LeetCode2:Add Two Numbers
- LeetCode2 Add Two Numbers
- leetCode2:Add Two Numbers
- leetcode2--Add Two Numbers
- leetcode2 Add Two Numbers
- LeetCode2:Add Two Numbers
- leetcode2 Add Two Numbers
- Leetcode2 Add Two Numbers
- LeetCode2.Add Two Numbers
- Leetcode2: Add Two Numbers
- LeetCode2. Add Two Numbers
- LeetCode2. Add Two Numbers
- leetcode2. Add Two Numbers
- leetcode2~Add Two Numbers
- LeetCode2.Add Two Numbers
- 拓展欧几里得算法
- DBCP连接池
- Longest Substring Without Repeating Characters (leetcode3)
- Wifi相关----WifiConfiguration+ScanResult
- EditText maxLines不工作
- Add Two Numbers (leetcode2)
- Intent传递对象的两种方法 && Parcelable AS插件 [U02]
- Jquery实现按回车调用别的单击事件(如按回车进行搜索)
- 关于 greenDao 注解实体类 序列化 [记录]
- [转载] 交叉验证(Cross Validation)简介
- HTML PC端常见布局
- Ubuntu14.04解决远程root-ssh拒绝登录
- Docker数据卷和数据卷容器
- 修改Ubuntu用户名和密码