Plus One

Plus One

问题:

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.

思路:

  思路很简单,遍历一遍,记录数值即可

我的代码:

public class Solution {
    public int[] plusOne(int[] digits) {
        if(digits == null || digits.length == 0)    return digits;
        int plus = 1;
        for(int i = digits.length - 1; i >= 0; i--)
        {
            int sum = digits[i] + plus;
            if(sum == 10)
            {
                digits[i] = 0;
                plus = 1;
            }
            else
            {
                digits[i] = sum;
                plus = 0;
            }
        }
        if(plus == 0)   return digits;
        else
        {
            int[] rst = new int[digits.length + 1];
            rst[0] = plus;
            for(int i = 1; i < rst.length; i++)
            {
                rst[i] = digits[i-1];
            }
            return rst;
        }
    }
}
View Code

他人代码:

public class Solution {  
    public int[] plusOne(int[] digits) {
        int carries = 1;
        for(int i = digits.length-1; i>=0 && carries > 0; i--){  // fast break when carries equals zero
            int sum = digits[i] + carries;
            digits[i] = sum % 10;
            carries = sum / 10;
        }
        if(carries == 0)
            return digits;
            
        int[] rst = new int[digits.length+1];
        rst[0] = 1;
        for(int i=1; i< rst.length; i++){
            rst[i] = digits[i-1];
        }
        return rst;
    }
}
View Code

学习之处:

  • carries变量命名不错
  • 用sum%10表示数值, sum/10表示进位,使程序简洁了好多,而且这种方法通用性比较强。

posted on 2015-03-08 19:51  zhouzhou0615  阅读(125)  评论(0编辑  收藏  举报

导航