Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] 다음 큰 숫자 #109

Closed
hwangJi-dev opened this issue Feb 14, 2023 · 0 comments
Closed

[Algorithm] 다음 큰 숫자 #109

hwangJi-dev opened this issue Feb 14, 2023 · 0 comments

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Feb 14, 2023

💬 문제

다음 큰 숫자


💬 Idea

  1. 현재 n을 2진수로 변환했을 때 1의 개수를 cnt에 저장해둔다.
  2. 다음 큰 수를 찾기 위해서 n + 1 부터 for문을 돌며 i를 2진수로 변환한다.
  3. 이 때 1의 개수가 cnt와 같다면 answer에 i를 저장하고 반복문을 탈출하여 조건을 만족하는 수 중 가장 작은 수를 찾는다.

💬 풀이

import Foundation

func solution(_ n:Int) -> Int
{
    var answer:Int = 0
    var cnt = String(n, radix: 2).filter({ $0 == "1" }).count
    
    for i in n + 1...1000000 {
        if cnt == String(i, radix: 2).filter({ $0 == "1" }).count {
            answer = i
            break
        }
    }
    
    return answer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant