Total Accepted: 78150 Total Submissions: 244950 Difficulty: Easy
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.
主要解题思路:不论carrier为多少,当前的值应为(digits[i]+carrier)%10,而carrier的值应该被重新赋为
(digits[i]+carrier)/10。
然后分两种情况考虑,无需进位的则直接返回,需要进位的只有一种情况:因为carrier==1的特殊性,全为9的情况,在这种情况下结果数组的位数比输入数组多一位。即输入{9, 9}输出{1, 0, 0}。
代码如下:
p
![]()
还有一种直接从carrier==1来考虑问题的做法,先check数组是不是全9,多循环了一遍digits数组,没有上一组做法更优。做法:
只须从数组尾部开始,若当前位是9则向前一位进位,小于9则直接将当前位加一返回即可。
public class Solution {
public int[] plusOne(int[] digits) {
int carrier = 1;
int n = digits.length-1;
for(int i = n; i>=0; i--){
int temp = digits[i]+carrier;
digits[i] = temp%10;
carrier = temp/10;
}
//如果没有进位,则digits为答案,代码到此为止都没有考虑carrier为1的特殊性。
if(carrier == 0) return digits;
int[] result = new int[n+2];
//这部分代码考虑了carrier为1的特殊性。加1进位的可能性只有第一位为1,后面都是0.比如[9,9]到[1,0,0].array默认值为0,因此只需要初始化第一位。
result[0] = 1;
return result;
}
}
package com.cwind.leetcode.math;
/**
* Created with IntelliJ IDEA.
* User: Cwind
* Date: 2015/7/1
* Email: billchen01@163.com
* #66 - Easy
*/
public class PlusOne {
public int[] plusOne(int[] digits) {
if(digits == null){
return null;
}
// check if it is all 9
boolean allNine = true;
for(int digit : digits){
if(digit!=9){
allNine = false;
}
}
if(allNine){
int result[] = new int[digits.length+1];
result[0] = 1;
return result;
}else {
for(int i=digits.length-1;i>=0;i--){
if(digits[i]<9){
digits[i]++;
break;
}else{
digits[i]=0;
}
}
}
return digits;
}
public static void main(String[] args){
PlusOne tester = new PlusOne();
int[] input = {1,2,3,9};
int[] output = tester.plusOne(input);
for(int i:output){
System.out.print(i);
}
int[] input2 = {9,9};
output = tester.plusOne(input2);
for(int i:output){
System.out.print(i);
}
}
}