您的位置:首页 > 其它

LeetCode2.1.17 @ Plus One 数组数字加一 D1F2

2014-07-17 02:42 246 查看
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.

初始定义carry=1,来用做PlusOne。时间复杂度O(n),空间复杂度O(1)。

如果到了MSB,最坏case是全部为9,那么需要重新建立array,赋值成[1,0,0...],空间复杂度上升为O(n)。

public class Solution {
public int[] plusOne(int[] digits) {
int carry=1;//for LSB, carry is the "PlusOne"
for(int i=digits.length-1;i>=0;i--){//【注意1】
int temp=digits[i]+carry;
digits[i]=temp%10;//【注意2】
carry=temp/10;//【注意3】
if(carry==0)//【注意4】
return digits;
}

int[] res=new int[digits.length+1];
res[0]=1;
return res;
}
}


【注意1】cuz the length may be 1,so avoid using "digits.length-2"。另外注意i--的循环,i>=0别写错,在此出过compile error

【注意2】x%10,取余实质是 x-10-10-10 直到不能再减得到的数。同理x%6

【注意3】使用x/10来表示carry,否则用if判断太复杂

【注意4】之前我的code把 if 放在循环外面,判断MSB是否进位;放在循环里面更节省资源,只要MSB之前没有进位,那么久不用构造新Array。

【后记】follow up问题:/article/1378285.html

“我觉得为什么Google喜欢的原因是后续可以问一些比较基本的扩展问题,比如可以扩展这个到两个数组相加,或者问一些OO设计,假设现在要设计一个BigInteger类,那么需要什么构造函数,然后用什么数据结构好,用数组和链表各有什么优劣势。这些问题虽然不是很难,但是可以考到一些基本的理解,所以平时准备有机会还是可以多想想哈。”

附:第一次写错的code

public class Solution {
public int[] plusOne(int[] digits) {
int carry=0;
for(int i=digits.length-1;i>=0;i--){
int temp=digits[i]+1+carry;
if(temp%10==0){
digits[i]=temp%10;
carry=1;
}
else{
digits[i]=temp%10;
carry=0;
}
}
if (carry==1){
int[] res=new int[digits.length+1];
res[0]=1;
return res;
}
else{
return digits;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: