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.
ExampleGiven [1,2,3]
which represents 123, return [1,2,4]
.
Given [9,9,9]
which represents 999, return [1,0,0,0]

比较简单的题,从尾到头遍历,然后如果有进位依次加一,最后在判断是否需要加一个数字到数组头。

public class Solution {
    /**
     * @param digits a number represented as an array of digits
     * @return the result
     */
    public int[] plusOne(int[] digits) {
        // Write your code here
        if(digits == null || digits.length < 1){
            return digits;
        }
        
        int adder = 1;
        for (int i = digits.length-1; i >= 0 && adder > 0; i--) {
            int sum  = digits[i] + adder;
            digits[i] = sum % 10;
            adder = sum / 10;
        }
        
        if(adder == 0){
            return digits;
        }
        
        int[] num = new int[digits.length + 1];
        num[0] = 1;
        for( int j = 1; j < digits.length; j++) {
            num[j] = digits[j-1];
        }
        return  num;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • 一直在和你说回家的事情,有时候晚上睡不着,就会想象我们一起回家的样子,一起慢慢地坐火车,在火车上看着窗边大片的麦田...
    老胡Boba阅读 152评论 0 0
  • 北京的秋其实挺冷的。 我是七月份到北京任职,那时真的是闷热。作为一个北方人,在我从出生到毕业的二十多年里,我经历过...
    彼岸浅酌阅读 257评论 0 0
  • 今天我的花店开张啦! 实现开花店的梦想,缘于我对开花店的目标感。在我的梦想中,一直有一个实实在在的卖花的小店,品种...
    楚楚云儿阅读 385评论 0 2