[LeetCode] 397. Integer Replacement

2020. 3. 24. 04:59ยท ๐Ÿ–ฅ๏ธ Computer/Algorithm Solution

Given a positive integer n and you can do operations as follow:

  1. If n is even, replace n with n/2.
  2. If n is odd, you can replace n with either n + 1 or n - 1.

What is the minimum number of replacements needed for n to become 1?

 

Example 1:

Input:

8

 

Output:

3

 

Explanation:

8 -> 4 -> 2 -> 1

 

Example 2:

Input:

7

 

Output:

4

 

Explanation:

7 -> 8 -> 4 -> 2 -> 1

or

7 -> 6 -> 3 -> 2 -> 1

 


์ฝ”๋“œ

class Solution {
public:
    int integerReplacement(int n) {
        long int k{n};
        int cnt{0};
        while(k!=1){
            if(k == 3)
                return cnt + 2;
            if(k%2 == 1){
                if((k-1)/2 % 2 == 1)
                    k+=1;
                else
                    k-=1;
            }
            else
                k/=2;
            cnt++;
        }
        return cnt;
    }
};

'๐Ÿ–ฅ๏ธ Computer > Algorithm Solution' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[BAEKJOON] 2960๋ฒˆ : ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด  (0) 2020.07.09
[LeetCode] 389. Find the Difference  (1) 2020.03.25
[LeetCode] 278. First Bad Version  (4) 2020.03.24
[LeetCode] 7. Reverse Integer  (1) 2020.03.23
[BAEKJOON] 7568๋ฒˆ : ๋ฉ์น˜  (0) 2020.03.20
'๐Ÿ–ฅ๏ธ Computer/Algorithm Solution' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€
  • [BAEKJOON] 2960๋ฒˆ : ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด
  • [LeetCode] 389. Find the Difference
  • [LeetCode] 278. First Bad Version
  • [LeetCode] 7. Reverse Integer
_์ฃผ๋…ธ
_์ฃผ๋…ธ
juno.log_์ฃผ๋…ธ ๋‹˜์˜ ๋ธ”๋กœ๊ทธ์ž…๋‹ˆ๋‹ค.
_์ฃผ๋…ธ
juno.log
_์ฃผ๋…ธ
์ „์ฒด
์˜ค๋Š˜
์–ด์ œ
  • ๋ถ„๋ฅ˜ ์ „์ฒด๋ณด๊ธฐ (88)
    • ๐Ÿ’ฌ Language (15)
      • C (1)
      • C++ (1)
      • Java (12)
    • ๐Ÿ–ฅ๏ธ Computer (46)
      • Data Structure (2)
      • Computer Science (3)
      • Algorithm Solution (41)
    • ๐ŸŒฑ Spring (14)
    • ๐Ÿ“ฆ Database (1)
    • ๐Ÿฅณ Project (6)
      • kakao chatbot (6)
    • ๐Ÿ˜† Daily (5)
      • ์žก๋‹ด (5)
      • TIL (0)

๋ธ”๋กœ๊ทธ ๋ฉ”๋‰ด

  • ํ™ˆ
  • ๋ธ”๋กœ๊ทธ ๊ด€๋ฆฌ
  • GitHub
  • Velog

์ธ๊ธฐ ๊ธ€

hELLO ยท Designed By ์ •์ƒ์šฐ.v4.2.0
_์ฃผ๋…ธ
[LeetCode] 397. Integer Replacement
์ƒ๋‹จ์œผ๋กœ

ํ‹ฐ์Šคํ† ๋ฆฌํˆด๋ฐ”

๊ฐœ์ธ์ •๋ณด

  • ํ‹ฐ์Šคํ† ๋ฆฌ ํ™ˆ
  • ํฌ๋Ÿผ
  • ๋กœ๊ทธ์ธ

๋‹จ์ถ•ํ‚ค

๋‚ด ๋ธ”๋กœ๊ทธ

๋‚ด ๋ธ”๋กœ๊ทธ - ๊ด€๋ฆฌ์ž ํ™ˆ ์ „ํ™˜
Q
Q
์ƒˆ ๊ธ€ ์“ฐ๊ธฐ
W
W

๋ธ”๋กœ๊ทธ ๊ฒŒ์‹œ๊ธ€

๊ธ€ ์ˆ˜์ • (๊ถŒํ•œ ์žˆ๋Š” ๊ฒฝ์šฐ)
E
E
๋Œ“๊ธ€ ์˜์—ญ์œผ๋กœ ์ด๋™
C
C

๋ชจ๋“  ์˜์—ญ

์ด ํŽ˜์ด์ง€์˜ URL ๋ณต์‚ฌ
S
S
๋งจ ์œ„๋กœ ์ด๋™
T
T
ํ‹ฐ์Šคํ† ๋ฆฌ ํ™ˆ ์ด๋™
H
H
๋‹จ์ถ•ํ‚ค ์•ˆ๋‚ด
Shift + /
โ‡ง + /

* ๋‹จ์ถ•ํ‚ค๋Š” ํ•œ๊ธ€/์˜๋ฌธ ๋Œ€์†Œ๋ฌธ์ž๋กœ ์ด์šฉ ๊ฐ€๋Šฅํ•˜๋ฉฐ, ํ‹ฐ์Šคํ† ๋ฆฌ ๊ธฐ๋ณธ ๋„๋ฉ”์ธ์—์„œ๋งŒ ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค.