๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/๋ฐฑ์ค€(BOJ)

[ ํŒŒ์ด์ฌ(python) ] ๋ฐฑ์ค€ 2231 - ๋ถ„ํ•ดํ•ฉ

by YWTechIT 2021. 5. 12.
728x90

๐Ÿ“ ๋ฐฑ์ค€ 2231 - ๋ถ„ํ•ดํ•ฉ

๋ฐฑ์ค€ 2231 - ๋ถ„ํ•ดํ•ฉ


โšก๏ธ ๋‚˜์˜ ํ’€์ด

์–ธ์  ๊ฐ€ ๋ฐฑ์ค€ ๋‹จ๊ณ„๋ณ„ ๋ฌธ์ œํ’€์ด์—์„œ ์ด ๋ฌธ์ œ๋ฅผ ๋ดค์—ˆ๋Š”๋ฐ ๊ทธ๋•Œ๋Š” ์ดํ•ด๊ฐ€ ์•ˆ ๋ผ์„œ ๊ทธ๋ƒฅ ๋„˜๊ฒจ๋ฒ„๋ ธ๋‹ค. ์ด๋ฒˆ์—” ์ง‘์ค‘ํ•ด์„œ ๋ฌธ์ œ๋ฅผ ์žก์•˜๋”๋‹ˆ ํ’€ ์ˆ˜ ์žˆ์—ˆ๋Š”๋ฐ ์‹œ๊ฐ„ ๋‹จ์ถ•ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋๋‚ด ์ฐพ์ง€ ๋ชปํ–ˆ๋‹ค.

 

๋ณดํ†ต ๋ธŒ๋ฃจํŠธ ํฌ์Šค์˜ ๋ฌธ์ œ์˜ ๋ฒ”์œ„๋Š” 1,000,000์œผ๋กœ ์ฃผ์–ด์ง€๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋งŽ๋‹ค. ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ๋ณผ ๋•Œ ๋ฒ”์œ„๊ฐ€ 1,000,000์ด๋ผ๋ฉด ๋ธŒ๋ฃจํŠธํฌ์Šค๋ฅผ ์˜์‹ฌํ•ด๋ณด์ž!

 

์ด 3๋ฒˆ์— ๊ฑธ์ณ์„œ ํ’€์—ˆ๊ณ , ์ฒซ ๋ฒˆ์งธ๋Š” ์‹œ๊ฐ„ ์ดˆ๊ณผ (์ฝ”๋“œ๋ฅผ ๋‹ค์‹œ๋ณด๋‹ˆ๊นŒ ์ƒ์„ฑ์ž๊ฐ€ ์—†๋Š” ์กฐ๊ฑด์„ ๊ณ ๋ คํ•˜์ง€ ์•Š๊ณ  ์„ค๊ณ„ํ•ด์„œ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚ฌ๋‹ค. (21. 5. 13.)), ๋‘๋ฒˆ์งธ๋Š” ์ •๋‹ตํŒ์ •์ด ๋‚ฌ์ง€๋งŒ ์‹คํ–‰์‹œ๊ฐ„์ด ๋งŽ์ด ๋‚˜์™”๋‹ค. ์„ธ ๋ฒˆ์งธ๋Š” ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ์ฝ”๋“œ ์ค‘ ์‹œ๊ฐ„ ์ตœ์ ํ™”๊ธฐ๋Šฅ๋งŒ ๊ฐ€์ ธ์™”๋‹ค.

 

  1. ์ž…๋ ฅ์„ ๋ฐ›๋Š”๋‹ค.
  2. target์˜ ๋ถ„ํ•ดํ•ฉ์„ ๊ตฌํ•˜๊ธฐ์œ„ํ•ด ํ•ด๋‹น ๊ฐ’์„ str๋กœ ๋ฐ”๊พธ๊ณ  ๊ฐ ์ž๋ฆฌ์ˆ˜๋ฅผ ๋ชจ๋‘ ๋”ํ•ด์ค€ ๊ฐ’์„ temp์— ๋„ฃ์–ด์ค€๋‹ค.
  3. ํ˜„์žฌ i๊ฐ’๊ณผ temp๋ฅผ ๋”ํ•œ ๊ฐ’์„ result๋กœ ์ดˆ๊ธฐํ™”์‹œํ‚จ๋‹ค.
  4. ๋งŒ์•ฝ result ๊ฐ’์ด target๊ณผ ๋™์ผํ•˜๋‹ค๋ฉด? ํ•ด๋‹น ๊ฐ’์€ ์ƒ์„ฑ์ž๋‹ค.
  5. ๋ฐ˜๋ณต๋ฌธ์„ ๋ชจ๋‘ ๋Œ์•˜๋Š”๋ฐ๋„ ์ƒ์„ฑ์ž๊ฐ€ ์—†๋‹ค๋ฉด 0์„ ์ถœ๋ ฅํ•œ๋‹ค. (for - else ๊ตฌ๋ฌธ)

 

์ด๋ ‡๊ฒŒ ์ •๋‹ตํŒ์ •์„ ๋ฐ›์•˜๋Š”๋ฐ 1376 m/s์ด ๊ฑธ๋ ธ๋‹ค. ์‹คํ–‰์‹œ๊ฐ„์ด ์ƒ๊ฐ๋ณด๋‹ค ๊ธธ์–ด์„œ ์ตœ์ ํ™”๊ฐ€ ํ•„์š”ํ•ด ๋ณด์˜€๋‹ค. ๋ฐ˜๋ณต๋ฌธ์˜ ์‹œ์ž‘ ๋ฒ”์œ„๋ฅผ ์ค„์ด๋ฉด ๋  ๊ฒƒ ๊ฐ™์€๋ฐ, ์–ด๋–ป๊ฒŒ ์ค„์—ฌ์•ผ ํ• ์ง€ ๊ฐ์ด ์˜ค์ง€ ์•Š์•˜๋‹ค.

 

์‹œ๊ฐ„ ์ตœ์ ํ™”ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

  1. ๋ถ„ํ•ดํ•ฉ์€ N๊ณผ N์˜ ๊ฐ ์ž๋ฆฟ์ˆ˜์˜ ํ•ฉ์ด๋‹ค.
  2. ๋ฐ˜๋Œ€๋กœ, ์ƒ์„ฑ์ž๋ฅผ ๊ตฌํ•˜๋ ค๋ฉด ๋ถ„ํ•ดํ•ฉ์„ ๊ตฌํ•˜๋Š” ๊ณผ์ • ์ค‘ N์€ ๋†”๋‘๊ณ  N์˜ ๊ฐ ์ž๋ฆฟ์ˆ˜์˜ ํ•ฉ๋งŒ ๋นผ์ฃผ๋ฉด ๋˜๋Š”๋ฐ, ์–ด๋–ค ์ˆ˜๊ฐ€ ๋‚˜์˜ฌ์ง€ ๋ชจ๋ฅด๋‹ˆ๊นŒ ๊ฐ ์ž๋ฆฟ์ˆ˜์— ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ์ˆ˜(0~9)์ธ 9๋ฅผ ๋นผ์ฃผ๋ฉด ๋œ๋‹ค.
  3. ๊ทธ๋Œ€๋กœ ์ ์šฉํ•˜๊ฒŒ ๋˜๋ฉด N์ด 0~9๊ฐ€ ๋‚˜์˜ฌ๋•Œ๋Š” ์Œ์ˆ˜๊ฐ€ ๋‚˜์˜จ๋‹ค. ๋”ฐ๋ผ์„œ ์ ˆ๋Œ“๊ฐ’(abs)์„ ์”Œ์›Œ์ฃผ์ž.

 

# ์ฒซ๋ฒˆ์งธ ์‹œ๋„: ์‹œ๊ฐ„ ์ดˆ๊ณผ
target = int(input())
n, result = 0, 0

while target != result:
    n += 1
    temp = sum(map(int, str(n))) 
    result = n + temp
print(n)
# ๋‘๋ฒˆ์งธ ์‹œ๋„: ์„ฑ๊ณต
target = int(input())

for i in range(target):
    temp = sum(map(int, str(i)))
    result = i + temp
    if result == target:
        print(i)
        break
else:
    print(0)
# ๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ์ฝ”๋“œ: ์‹œ๊ฐ„ ์ตœ์ ํ™”
target = int(input())
min_target = abs(target - (len(str(target)) * 9))

for i in range(min_target, target):
    temp = sum(map(int, str(i)))
    result = i + temp
    if result == target:
        print(i)
        break
else:
    print(0)

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€