[Leetcode]--Plus One

Given a number represented as an array of digits, plus one to the number.

 

[Leetcode]--Plus One
public class Solution {
    public int[] plusOne(int[] digits) {
        int carry = 0;
        int length = digits.length;
        
        digits[length-1] = digits[length -1] + 1;
        for(int i = length -1 ; i>=0; i--){
            digits[i] += carry;
            carry = 0;
            if(digits[i] >= 10) {
                carry = digits[i] /10;
                digits[i] = digits[i]%10;
            }
        }
        
        if(carry != 0) {
         int[] result = new int[length+1];
         result[0] = carry;
         
         for(int j = 1; j< length+1; j++){
             result[j] = digits[j-1];
         }
         return result;
        } else {
            return digits;
        }
        
    }
}
[Leetcode]--Plus One

[Leetcode]--Plus One

上一篇:新北市3D打印研讨会,马路科技分享成功经验


下一篇:codeforces C. Ilya and Matrix 解题报告