LeetCode 66 Plus One
2018-01-15 14:15
471 查看
原题:
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.
题意:
一个整数按位存储于一个int数组中,排列顺序为:最高位在digits[0] ,最低位在digits[n-1],
例如,98,存储为:digits[0]=9; digits[1]=8;
代码及思路:
class Solution {
public int[] plusOne(int[] digits) {
//解题思路:从数组的最后一位开始加1,需要考虑进位,如果到digits[0]位之后仍然有进位存在,则将进位加上
int n = digits.length;
for(int i=n-1;i>=0;i--){
if(digits[i]<9){
digits[i]++;
return digits;
}
//如果不是<9,那就是等于9,把当前位置设置为0后,for循环会继续判断前面一位,如果<9,digits[i]++会自动进位
digits[i] = 0;
}
//如果最后一位也等于9,如(99)那么就没有return,进入这一步
int [] newA = new int [n+1];
newA[0] = 1;
return newA;
}
}
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.
题意:
一个整数按位存储于一个int数组中,排列顺序为:最高位在digits[0] ,最低位在digits[n-1],
例如,98,存储为:digits[0]=9; digits[1]=8;
代码及思路:
class Solution {
public int[] plusOne(int[] digits) {
//解题思路:从数组的最后一位开始加1,需要考虑进位,如果到digits[0]位之后仍然有进位存在,则将进位加上
int n = digits.length;
for(int i=n-1;i>=0;i--){
if(digits[i]<9){
digits[i]++;
return digits;
}
//如果不是<9,那就是等于9,把当前位置设置为0后,for循环会继续判断前面一位,如果<9,digits[i]++会自动进位
digits[i] = 0;
}
//如果最后一位也等于9,如(99)那么就没有return,进入这一步
int [] newA = new int [n+1];
newA[0] = 1;
return newA;
}
}
相关文章推荐
- 2017.10.22 LeetCode - 35. Search Insert Position - 66. Plus One
- 【LeetCode】66. Plus One
- 【一天一道LeetCode】#66. Plus One
- 【Leetcode】66. Plus One
- LeetCode *** 66. Plus One
- Leetcode 66 Plus One
- LeetCode66. Plus One
- [leetcode] 66.Plus One
- [leetcode]: 66. Plus One
- leetcode题解-121. Best Time to Buy and Sell Stock && 122. Best Time to Buy and Sell St && 66. Plus One
- leetcode 66. Plus One
- [Leetcode]#66 Plus One
- LeetCode 第 66 题 (Plus One)
- LeetCode 66 Plus One
- [LeetCode 66] Plus One
- 2018.3.12 leetcode打卡 #66 plus one
- [leetcode]66. Plus One(Java)
- LeetCode_66. Plus One_数组加一
- 【leetcode】66. Plus One【java】
- LeetCode 66. Plus One