美文网首页
[LeetCode] No.66 Plus One

[LeetCode] No.66 Plus One

作者: yuansc | 来源:发表于2016-10-14 11:02 被阅读38次

链接:https://leetcode.com/problems/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.

分析:
没别的方法,就是加,但是要注意进1位,总感觉这不是算法题,是细节题.

public class Solution {
    public int[] plusOne(int[] digits) {
         if (digits.length == 0) {
            return new int[]{1};
        }
        int carry = 1;
        for (int i = digits.length - 1; i >= 0; i--) {
            int value = digits[i] + carry;
            carry = value/10;
            digits[i] = value%10;
            if(carry == 0) {
                break;
            }
        }
        if(carry == 1) {
            int[] one = new int[digits.length+1];
            one[0] = 1;
            for(int i=1;i<digits.length+1;i++) {
                one[i] = digits[i-1];
            }
            return one;
        } else {
            return digits;
        }
    }
}

相关文章

网友评论

      本文标题:[LeetCode] No.66 Plus One

      本文链接:https://www.haomeiwen.com/subject/mvmgyttx.html