Tuesday, June 17, 2014

Leetcode - 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.
[Thoughts]: 这个题唯一的亮点就应该是用到arraycopy那个方法吧。
public class Solution {
    public int[] plusOne(int[] digits) {
        int carry = 1;
        int sum = 0;
        for(int i = digits.length-1; i>=0; i--){
            sum = carry+digits[i];
            carry = sum/10;
            digits[i] = sum%10;
        }
        if(carry>0){
            int[] res = new int[digits.length+1];
            res[0] = carry;
            System.arraycopy(digits,0,res, 1, digits.length);
            return res;
        }
        return digits;
    }
}

No comments:

Post a Comment