[LeetCode] Keep Multiplying Found Values by Two

준규·2022년 12월 16일

1. 문제

You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums.

You then do the following steps:

If original is found in nums, multiply it by two (i.e., set original = 2 * original).

Otherwise, stop the process.

Repeat this process with the new number as long as you keep finding the number.

Return the final value of original.


nums 라는 숫자배열에 original 이 존재한다면 계속 2를 곱해나간다. 만약 original이 존재 하지 않는 순간이라면 그때의 original을 리턴하는 문제이다.


Example 1

Input: nums = [5,3,6,1,12], original = 3
Output: 24
Explanation: 
- 3 is found in nums. 3 is multiplied by 2 to obtain 6.
- 6 is found in nums. 6 is multiplied by 2 to obtain 12.
- 12 is found in nums. 12 is multiplied by 2 to obtain 24.
- 24 is not found in nums. Thus, 24 is returned.

Example 2

Input: nums = [2,7,9], original = 4
Output: 4
Explanation:
- 4 is not found in nums. Thus, 4 is returned.

Constraints:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i], original <= 1000

2.풀이

  1. while 문을 돌면서 배열안에 original이 포함되는지 체크한다.
  2. 만약 포함된다면 original 값을 2배하여 새로 할당한다.

/**
 * @param {number[]} nums
 * @param {number} original
 * @return {number}
 */
const findFinalValue = function (nums, original) {
  while (1) {
    if (nums.includes(original)) {
      // nums에 original이 존재하는지 체크
      original *= 2; // 존재한다면 2배
    } else {
      return original; // 아니라면 original return
    }
  }

  return original;
};

3.결과

profile
안녕하세요 :)

0개의 댓글