您的位置:首页 > 编程语言 > Java开发

Plus One Java

2014-08-28 08:57 211 查看
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.

 Idea:

    Read digits from back to front

    find reminder by % operation

    and Carry by / operation

    Time: O(N) Space: worst case O(N),normal case O(1)
public class Solution {
public int[] plusOne(int[] digits) {
if(digits.length==0) return digits;
int plusOne=1;
int carry=0;
for (int i=digits.length-1;i>=0;i--){
//reminder % and carray / operation
int reminder=(digits[i]+plusOne)%10;
carry=(digits[i]+plusOne)/10;
//assign new digit to position i
digits[i]=reminder;
//no carry was found
if(carry==0){
return digits;
}
}
//to handle the special case of all digits is number 9
int[] res=new int[digits.length+1];
//need add-on for carry
res[0]=1;
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: