프로그래밍
프로그래머스 C# 다음 큰 숫자(이진수 변환, 이진법, Convert.ToString, Convert.ToInt32, JAVA)
노마드선샤인
2023. 1. 22. 15:07
728x90
using System;
class Solution
{
public int solution(int n)
{
int answer = 0;
string ijin2 = "";
string result = "";
string ijin = Convert.ToString(n, 2); /// n을 이진수로 바꾸기
ijin = ijin.Replace("0", ""); // 0을 삭제하기
for(int i=n+1;i<=1000000;i++)
{
ijin2 = Convert.ToString(i, 2);
result = ijin2.Replace("0", ""); /// 1의 개수가 같으면 되니까 0을 지우고 1로만 세팅한다.
if(ijin.Length == result.Length) // 1로만 세팅된 게 같으면 break한다.
{
break;
}
}
answer = Convert.ToInt32(ijin2, 2); //이 숫자를 다시 2진수로 바꾼다.
return answer;
}
}
자바
class TryHelloWorld
{
public int nextBigNumber(int n)
{
int cnt = Integer.bitCount(n);
while(Integer.bitCount(++n) != cnt) {}
return n;
}
public static void main(String[] args)
{
TryHelloWorld test = new TryHelloWorld();
int n = 78;
System.out.println(test.nextBigNumber(n));
}
}
class TryHelloWorld {
public int nextBigNumber(int n) {
int postPattern = n & -n, smallPattern = ((n ^ (n + postPattern)) / postPattern) >> 2;
return n + postPattern | smallPattern;
}
public static void main(String[] args) {
int n = 78;
System.out.println(new TryHelloWorld().nextBigNumber(n));
}
}
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class TryHelloWorld
{
public int nextBigNumber(int n)
{
int answer = n;
int defaultCnt = Integer.bitCount(n);
while(true)
{
answer++;
if(Integer.bitCount(answer) == defaultCnt)
break;
}
return answer;
}
public static void main(String[] args)
{
TryHelloWorld test = new TryHelloWorld();
int n = 78;
System.out.println(test.nextBigNumber(n));
}
}
728x90