Plus One Java

来源:互联网 发布:linux crontab每秒 编辑:程序博客网 时间:2024/06/13 07:44

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.


 Idea:
    Read digits from back to front
    find reminder by % operation
    and Carry by / operation
    Time: O(N) Space: worst case O(N),normal case O(1)
public class Solution {    public int[] plusOne(int[] digits) {        if(digits.length==0) return digits;        int plusOne=1;        int carry=0;        for (int i=digits.length-1;i>=0;i--){            //reminder % and carray / operation            int reminder=(digits[i]+plusOne)%10;            carry=(digits[i]+plusOne)/10;            //assign new digit to position i            digits[i]=reminder;            //no carry was found            if(carry==0){                return digits;            }        }        //to handle the special case of all digits is number 9        int[] res=new int[digits.length+1];        //need add-on for carry        res[0]=1;        return res;    }}


0 0
原创粉丝点击