쩨이엠 개발 블로그

[ Leetcode ] 66. Plus One - Java 본문

개발/Programming

[ Leetcode ] 66. Plus One - Java

쩨이엠 2021. 1. 26. 21:48
728x90
반응형

Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

 

 
 Example 1:

 Input: digits = [1,2,3] 
 Output: [1,2,4] 
 Explanation: The array represents the integer 123.
 
 
 Example 2:

 Input: digits = [4,3,2,1] 
 Output: [4,3,2,2] 
 Explanation: The array represents the integer 4321.
 
 
 Example 3:

 Input: digits = [0] 
 Output: [1]
 

 

Constraints:

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9

 

 
 import java.math.BigInteger;

 class Solution {
    public int[] plusOne(int[] digits) {
        
        //더하고 확인
        digits[digits.length-1]+=1;
        
        //더했을 때 10인 경우
        if(digits[digits.length-1] == 10){
             
            int digit = 0;
            for(int i=digits.length-1; i>=0; i--){
            	//뒤에서부터 10인 경우 위로 1씩 올린 후 0으로 바꿔준다
                if(i == 0 && digits[i] == 10){
                    int[] answerArr = new int[digits.length+1];
                    for(int j=1; j< digits.length; j++){
                        answerArr[j] = digits[j];
                    }
                    answerArr[0] = 1;
                    answerArr[1] = 0;
                    return answerArr;
                    
                }
                //10이 아닌 경우 break
                if(digits[i] == 10){
                    digits[i] = 0;
                    digits[i-1] += 1;
                }else{
                    break;
                }
            }
           
            return digits;
        }
            
        return digits;
        
    }
 }
 

 

728x90
반응형
Comments