leetcode-Add Tow Numbers
来源:互联网 发布:linux解包boot.img 编辑:程序博客网 时间:2024/06/08 05:13
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
思路:链表虽然是反置的,但是进位的方向是正确的,随意两个链表都从头遍历,进行就算就可以。计算中遇到一个链表为空时,其值置为0,只有当两个链表都为空时,才终止计算
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null) return l2; if(l2 == null) return l1; ListNode ansList = new ListNode(0), head = ansList; int flag = 0; while(true){ if(l1 == null && l2 == null){ if(flag == 1){ ansList.next = new ListNode(flag); } break; } int add1 = l1==null ? 0:l1.val; int add2 = l2==null ? 0:l2.val; int sum = add1+add2+flag; flag = sum/10; ListNode node = new ListNode(sum%10); ansList.next = node; ansList = node; if(l1 != null){ l1 = l1.next; } if(l2 != null){ l2 = l2.next; } } return head.next; }}
阅读全文
0 0
- leetcode: Add Tow Numbers
- leetcode-Add Tow Numbers
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode : Add Two Numbers
- 【leetcode】Add Two Numbers
- [LeetCode]Add Two Numbers
- leetcode Add Two Numbers
- LeetCode-Add Two Numbers
- [leetcode] Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode - Add Two Numbers
- 为什么Git 比 SVN 好
- OpenGL-渲染管线的流程(有图有真相)
- 聊聊全栈
- 浅谈屏幕取词划词与API HOOK、远程注入的关系以及技术原理
- sublime3 汉化
- leetcode-Add Tow Numbers
- 09:整型与布尔型的转换
- Hololens的世界坐标理解
- iOS10 权限以及相关设置
- Combinations 乘法逆元
- 欢迎使用CSDN-markdown编辑器
- Git常用命令
- Laravel5 内置登录注册使用教程
- 51nod 1050 循环数组的最大子段和