๋ฌธ์ ์ค๋ช
์์ฐ์ n์ด ์ฃผ์ด์ก์ ๋, n์ ๋ค์ ํฐ ์ซ์๋ ๋ค์๊ณผ ๊ฐ์ด ์ ์ ํฉ๋๋ค.
์กฐ๊ฑด 1. n์ ๋ค์ ํฐ ์ซ์๋ n๋ณด๋ค ํฐ ์์ฐ์ ์
๋๋ค.
์กฐ๊ฑด 2. n์ ๋ค์ ํฐ ์ซ์์ n์ 2์ง์๋ก ๋ณํํ์ ๋ 1์ ๊ฐฏ์๊ฐ ๊ฐ์ต๋๋ค.
์กฐ๊ฑด 3. n์ ๋ค์ ํฐ ์ซ์๋ ์กฐ๊ฑด 1, 2๋ฅผ ๋ง์กฑํ๋ ์ ์ค ๊ฐ์ฅ ์์ ์ ์
๋๋ค.
์๋ฅผ ๋ค์ด์ 78(1001110)์ ๋ค์ ํฐ ์ซ์๋ 83(1010011)์
๋๋ค.
์์ฐ์ n์ด ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง ๋, n์ ๋ค์ ํฐ ์ซ์๋ฅผ return ํ๋ solution ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์.
์ ํ ์ฌํญ
n์ 1,000,000 ์ดํ์ ์์ฐ์ ์
๋๋ค.
์ ์ถ๋ ฅ ์
n | result |
---|---|
78 | 83 |
15 | 23 |
์ ์ถ๋ ฅ ์ ์ค๋ช
์ ์ถ๋ ฅ ์#1
๋ฌธ์ ์์์ ๊ฐ์ต๋๋ค.
์ ์ถ๋ ฅ ์#2
15(1111)์ ๋ค์ ํฐ ์ซ์๋ 23(10111)์ ๋๋ค.
๋ฌธ์ ํ์ด
def solution(n):
bin_number = bin(n)[2:]
bin_ = "0b1" + bin_number # ์์๋ก 2์ง์ 11001 >> 111001
for i in range(n+1, int(bin_, 2)+1): # 10์ง์๋ก ๋ณํํ์ฌ ๋ฒ์ ์ค์
if bin(i)[2:].count("1") == bin_number.count("1"): # 1์ ๊ฐ์๊ฐ ๊ฐ์ผ๋ฉด
return i # ํด๋นํ๋ ์ซ์๋ฅผ return
break
๋ค๋ฅธ ์ฌ๋ ํ์ด
๋ฌดํ Loop๋ฅผ ์ฌ์ฉ
def nextBigNumber(n, count = 0):
return n if bin(n).count("1") is count else nextBigNumber(n+1, bin(n).count("1") if count is 0 else count)
์ง์ ๋ณํ ํจ์
2์ง์ : bin()
/ 0b
8์ง์ : oct()
/ 0o
16์ง์ : hex()
/ 0x
10์ง์ : int('๋ณํํ ์ซ์','x ์ง์)
format()์ผ๋ก ์ง์ ๋ณํ์ด ๊ฐ๋ฅํ๋ค
format('๋ณํํ ์ซ์', '์ง์ ๊ฐ')
์ง์ ๊ฐ : 2(b), 8(o), 10(d), 16(x)
์ง์ ๊ฐ ์์ #๋ฅผ ๋ถ์ด๋ฉด ์ ๋์ด ํฌํจ์ด ๊ฐ๋ฅํ๋ค
"{0:d}, {0:b}, {0:o}, {0:x}".format(77)
>>> 77, 1001101, 115, 4d