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;

            }

        }
}
發佈了93 篇原創文章 · 獲贊 15 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章