개발에 AtoZ까지

[JAVA][Array] PlusOne 본문

코딩테스트 준비/기타문제

[JAVA][Array] PlusOne

AtoZ 개발자 2021. 2. 1. 17:03
반응형

1. 문제

Given a non-empty array of digits representing a non-negative integer, plus 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 contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.

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

2. 문제해설

Input으로 문자형 숫자를 주는데 그 숫자에서 +1을 해서 1개씩 split한 문자열로 반환하라

 

3. 코드포맷

public class PlusOne {

	public static void main(String[] args) {
		int[] digits = {2,1,9,9,9};
		int[] result = plusOne(digits);
		for (int i : result)
			System.out.println("val: " + i);
	}

}

 

4. 접근 방법

주어진 배열의 끝자리부터 +1를 해서 새로운 배열에 담아준다.  만약 10이상일 경우에는 0을 넣고  다음자리수에 +1를 해준다. 

5. 코드

public class PlusOne {

	public static void main(String[] args) {
		int[] digits = {2,1,9,9,9};
		int[] result = plusOne(digits);
		for (int i : result)
			System.out.println("val: " + i);
	}
    	private static int[] plusOne(int[] digits) {
		int index = digits.length-1;
		int plus=1;
		while(index>=0&&plus!=0) {
			digits[index]=(digits[index]+plus)%10;
			//10보다 작은 수여서 다음자릿수에 1를 하지 않아도 되는경우
			if(digits[index]!=0) {
				plus=0;
			}
			--index;
		}
		if(plus==1) {
			digits=new int[digits.length+1];
			digits[0]=1;
		}
		return digits;
	}

}

 

반응형
Comments