2014年4月18日 星期五

[LeetCode] Plus One

Problem:
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.
Solution:O(n)
public class Solution {
    public int[] plusOne(int[] digits) {
        for(int i = digits.length-1; i>=0; i--){
            if(digits[i] != 9){
                digits[i]++;
                return digits;
            }
            else{
                digits[i] = 0;
            }
        }
        
        int[] ret = new int[digits.length+1];
        ret[0] = 1;
        return ret;
    }
}

沒有留言:

張貼留言