[leetcode] Plus One
2015-09-13 11:39
330 查看
Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list.
例如:98,存储为:array[0]=9; array[1]=8。
思路:从数组的最后一位开始加1,需要考虑进位,如果到[0]位之后仍然有进位存在,需要新开一个长度为 digits.length + 1 的数组,拷贝原数组到该数组中。
JAVA代码:
public int[] plusOne(int[] digits) { if (digits == null || digits.length == 0) { return null; } int top = 0; int flag = 1; int i = digits.length - 1; int[] tmp = null; while (i >= 0) { if (top > 0) { int sum = digits[i] + top; if (sum >= 10) { top = 1; digits[i] = sum - 10; } else { digits[i] = sum; top = 0; } } if (flag == 1) { int sum = digits[i] + 1; if (sum >= 10) { top = 1; digits[i] = sum - 10; } else { digits[i] = sum; } flag = 0; } if (top == 0) { break; } else { i --; } } if (top > 0) { tmp = new int[digits.length + 1]; tmp[0] = top; for (int j = 1; j < tmp.length; j++) { tmp[j] = digits[j - 1]; } } return tmp == null ? digits : tmp; }
相关文章推荐
- js中arguments的用法
- angularjs 学习日志01
- static静态修饰符
- Objective-C学习-数组排序问题
- 9.11学习内容+周总结
- 选择跟程序员约会的10个理由
- Dubbo搭建例子
- Command-通过命令转发接受者/Chain of Resposibility客户端调整处理函数顺序
- lastNum与ifFirst
- CentOS7中启动/停止/重启服务命令
- 程序员周末都喜欢做什么?
- Andrew Ng Machine Learning 专题【Neural Networks】下
- Facebook上程序员的爆笑故事
- JS网址正则验证
- 南通大学2015-2016年1学期《软工》作业点评总结
- HashMap线程不安全问题
- Fragment与Activity进行通信
- 程序员笑话:只有程序猿才看得懂
- Stop Working More Than 40 Hours a Week BY GEOFFREY JAMES @SALES_SOURCE
- 利用SSIS的ForcedExecutionResult 属性 和CheckPoint调试Package