Plus One

신병규·2022년 9월 21일
0

Algorithm

목록 보기
3/6

정수 배열 숫자로 표현되는 큰 정수가 주어집니다. 여기서 각 숫자 [ i ]는 정수의 i 번째 숫자입니다. 숫자는 왼쪽에서 오른쪽으로 가장 유의한 것부터 가장 유의하지 않은 것까지 순서대로 정렬됩니다. 큰 정수에는 선행 0이 없습니다.

큰 정수를 1씩 증가시키고 결과 자릿수 배열을 반환합니다.

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:

Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
Example 3:

Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
 for(var i = digits.length - 1; i >= 0; i--){
    if(++digits[i] > 9) digits[i] = 0;
    else return digits;
  }
  digits.unshift(1);
  return digits; 
};

digits에 증감식 적용으로 해결

js 증감 연산자
++i는 변수 i의 값을 1 증가시킵니다. 동시에 ++i의 값도 1 증가시킵니다.

<script>
  var i = 1;

  document.write(++i, '<br>');
  document.write(i);
</script>

i++
i++는 변수 i의 값을 1 증가시킵니다. 하지만 i++ 자체는 바로 증가되지 않습니다.

<script>
  var i = 1;

  document.write(i++, '<br>');
  document.write(i);
</script>

0개의 댓글