66. Plus One(java)
来源:互联网 发布:矩阵的奇异值分解方法 编辑:程序博客网 时间:2024/06/09 23:04
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
思路:从数组的最后一位往前开始加1,需要考虑进位。如果到数组0位时仍有进位,新开一个长度为length + 1的数组。
方法一:
public class Solution { public int[] plusOne(int[] digits) { int c=1; for(int i=(digits.length-1);i>=0;i--){ int a=digits[i]+c; c=a/10; digits[i]=a%10; } if(c==1){ int[] newDigits=new int[digits.length+1]; newDigits[0]=1; for(int i=0;i<digits.length;i++){ newDigits[i+1]=digits[i]; } return newDigits; } return digits; }}
方法二:对数组的每一位,如果值小于9,直接使该位的值加一,并返回当前数组;如果等于9,令该位为0;依次遍历到第0位后,如果还存在进位,则说明原数组的所有位都为9,直接返回一个新建的一个长度加1、首位为1的数组。
public class Solution { public int[] plusOne(int[] digits) { int n = digits.length; for(int i=n-1; i>=0; i--) { if(digits[i]<9) { digits[i]++; return digits; } digits[i] = 0; } int[] res = new int[n+1]; res[0] = 1; return res; }}
阅读全文
0 0
- 66. Plus One(java)
- (Java)LeetCode-66. Plus One
- 【leetcode】66. Plus One【java】
- [LeetCode] 66. Plus One java
- [leetcode]66. Plus One(Java)
- Leetcode:66. Plus One(JAVA)
- 66. Plus One(Java) & 43. Multiply Strings
- 66. Plus One —— Java
- [Leetcode] Plus One (Java)
- Plus One Java
- Plus One (Java)
- [LeetCode][Java] Plus One
- (java)Plus One
- plus-one java
- [LeetCode]66.Plus One
- LeetCode --- 66. Plus One
- [Leetcode] 66. Plus One
- [leetcode] 66.Plus One
- linux常用的正则表达式
- 简单计算器
- 字符编码
- PHP中安装redis扩展
- robolectric完全解析
- 66. Plus One(java)
- 二分查找模板C++
- HTML5 LocalStorage本地存储和sessionStorage使用
- C++中关于菱形继承
- 动态规划-钢条切割问题
- java 双重检查加锁弊端
- Android引用Library的若干问题(全都是坑啊,一定要注意了)
- 使用线程池ExecutorService实现并行查询
- 抽象类和接口