๋ฐฑ์ค€ A->B(Swift)

2022. 10. 24. 14:41ใ†Algorithm

๋ฐฑ์ค€ A->B(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

https://www.acmicpc.net/problem/16953

 

16953๋ฒˆ: A → B

์ฒซ์งธ ์ค„์— A, B (1 ≤ A < B ≤ 109)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net

 

 ๋‚˜์˜ ํ’€์ด

 

์ฒ˜์Œ์— n์˜ ๋งˆ์ง€๋ง‰ ์ˆซ์ž๊ฐ€ 1๋กœ๋๋‚˜๋Š” ๊ฒฝ์šฐ์™€ 2๋กœ ๋‚˜๋ˆ ๋–จ์–ด์ง€๋Š” ๊ฒฝ์šฐ ๋‘ ๊ฐ€์ง€๋งŒ ์ฒดํฌํ•ด์„œ ์ •๋‹ต์ด ์•ˆ ๋‚˜์™”์—ˆ๋Š”๋ฐ ๋‘๊ฐœ์˜ ๊ฒฝ์šฐ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ๋„ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ทธ ๊ฒฝ์šฐ๋ฅผ else { break }๋กœ ์ฒดํฌํ•ด์คฌ๋”๋‹ˆ ๋ฌธ์ œ๊ฐ€ ํ•ด๊ฒฐ๋˜์—ˆ๋‹ค.

 

import Foundation

let input = readLine()!.components(separatedBy: " ").map{Int($0)!}
var target = input[0], n = input[1]
var cnt = 1
while n > target {
    cnt += 1
    if String(n).last! == "1" {
        n = Int(String(n).prefix(String(n).count-1))!
    } else {
        if n % 2 == 0 {
            n = n / 2    
        } else {
            break
        }
    }
}
if n == target { print(cnt) }
else { print(-1) }

 

 ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

 

1์˜์ž๋ฆฌ๋ฅผ 10์œผ๋กœ ๋‚˜๋ˆ ์„œ ๊ตฌํ•œ ํ’€์ด๋‹ค. ์Šค์œ„ํ”„ํŠธ์—์„œ ์œ„์˜ ๋‚ด ํ’€์ด์ฒ˜๋Ÿผ ๋ฌธ์ž์—ด๋กœ ๋‹ค๋ฃจ๋ ค๊ณ ํ•˜๋ฉด ๋‹ค์†Œ ๋ณต์žกํ•œ ๋ถ€๋ถ„์ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ˆซ์ž์—์„œ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์œผ๋ฉด ๋˜๋„๋ก ์ˆซ์ž์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒŒ ์ข‹๋‹ค.

 

import Foundation

let input = readLine()!.components(separatedBy: " ").map{Int($0)!}
var target = input[0], n = input[1]
var cnt = 1
while n > target {
    if n%10 == 1 {
        n = n/10
    } else if n%2 == 0 {
        n = n/2
    } else {
        break
    }
    cnt += 1
}
if n == target { print(cnt) }
else { print(-1) }

 

 ํ”ผ๋“œ๋ฐฑ