[LeetCode] 13.Plus One

2021. 1. 17. 12:27

leetcode.com/problems/plus-one/

 

Plus One - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

1. Problem

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

2. Code

package leetcode;

public class PlusOne {
	public static void main(String[] args) {
		int[] input = {9,8,7,6,5,4,3,2,1,0};

		int[] result = plusOne(input);
		for(int i = 0 ; i < result.length; i++) {
			System.out.println(result[i]);
		}
	}
	
    public static int[] plusOne(int[] digits) {
    	boolean up = true;
    	for(int i = 0; i < digits.length; i++) {
    			if(up) {
        			digits[digits.length-1-i]++;
        		}
        		if(digits[digits.length-1-i] >= 10) {
        			up = true;
        			digits[digits.length-1-i] -= 10;
        			if(i == digits.length-1) {
        				int[] result = new int[digits.length+1];
            			for(int j = 0 ; j < result.length; j++) {
            				if(j==0) {
            					result[j] = 1;
            				} else {
            					result[j] = digits[j-1];
            				}
            			}
            			return result;
        			}
        		} else {
        			up = false;
        		}
    		}
        return digits;
    }
}

 

3.Report

지금까지 푼 문제들이랑 비슷한 방식으로 풀었다.

BELATED ARTICLES

more