码迷,mamicode.com
首页 > 其他好文 > 详细

Plus One

时间:2015-03-08 21:22:25      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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表示进位,使程序简洁了好多,而且这种方法通用性比较强。

Plus One

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4322164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!