leetcode 66. 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.

public class Solution {
  public int[] plusOne(int[] digits) {

            int j=digits.length-1;
            digits[j]+=1;
            while(j>0){
                if(digits[j]>9){
                    digits[j]=digits[j]-10;
                    digits[j-1]+=1;
                }

                j--;
            }


            if(digits[0]<10){
                return digits;
            }else
            {
                 int carry=0;
                 if(digits[0]>9){
                        digits[0]=digits[0]-10;
                        carry=1;
                 }
                 int[] ret=new int[digits.length+1];
                 ret[0]=carry;
                 for(int i=1;i<ret.length;i++){
                     ret[i]=digits[i-1];
                 }
                 return ret;

            }

        }
}
阅读更多
文章标签: leetcode 加一
个人分类: Leetcode
上一篇leetcode 101. Symmetric Tree
下一篇leetcode 26. Remove Duplicates from Sorted Array
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭