Skip to content

[Algorithm] 다음 큰 숫자 #109

Description

@hwangJi-dev

💬 문제

다음 큰 숫자


💬 Idea

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

💬 풀이

import Foundation
func solution(_ n:Int)->Int{varanswer:Int=0varcnt=String(n, radix:2).filter({ $0 =="1"}).count
foriin n +1...1000000{if cnt ==String(i, radix:2).filter({ $0 =="1"}).count {
answer = i
break}}return answer
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions