程序员面试金典 2.5 链式A+B
来源:互联网 发布:如何破解收银软件 编辑:程序博客网 时间:2024/05/16 01:42
题目
有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。
给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。
我的题解
import java.util.*;/*public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; }}*/public class Plus { public ListNode plusAB(ListNode a, ListNode b) { // write code here int offset = 1; int up = 0; ListNode res = null; ListNode cur = null; while((a != null) && (b != null)) { int sum = up; up = 0; sum += a.val + b.val; if(sum >= 10) { up = 1; } sum = sum % 10; if(res == null) { res = new ListNode(sum); cur = res; }else { cur.next = new ListNode(sum); cur = cur.next; } a = a.next; b = b.next; } ListNode now = a != null?a:b; while(now != null) { int sum = up; sum += now.val; if(sum >= 10) { up = 1; }else up = 0; sum = sum % 10; cur.next = new ListNode(sum); cur = cur.next; now = now.next; } if(up != 0) cur.next = new ListNode(up); return res; }}
0 0
- 《程序员面试金典》链式A+B
- [程序员面试金典]-链式A+B
- 程序员面试金典 2.5 链式A+B
- 程序员面试金典题解 链式A+B
- 程序员面试金典——链式A+B
- 链式A+B之程序员面试经典
- 程序员面试金典第二章:链表(5) 链式A+B
- 程序员面试金典:链表--链式A+B、回文链表
- 算法2.5:链式A+B
- 链式A+B
- 链式A+B
- 牛客网 | 链式A+B
- 链式A+B
- 链式A+B
- 链式A+B
- 链式A+B
- 《Cracking the Coding Interview程序员面试金典》----链表A+B
- 程序员面试金典--面试28之改变几个位,才能将整数A转变成整数B。
- jquery1.9判断浏览器类型
- 新手学习opencv四:Mat和IplImage简单处理图像耗时
- CV技术公司列表
- linux基本命令认识,shell打渠道包
- 裘宗燕:C/C++ 语言中的表达式求值
- 程序员面试金典 2.5 链式A+B
- Listiew的Item点击无反应(在item中有Button等抢焦点的控件存在时)
- localtime、localtime_s、localtime_r的使用
- js模仿java格式化字符串处理
- hibernate工作原理
- Structs开发整理
- nginx负载均衡简单配置
- 后端开发面试题大集合
- Symbol 'ANDROID_LOG_DEBUG' could not be resolved