JAVA를 이용하여 10진수를 2진수로 변환하는 방법 6가지를 정리해보았다.
public class BinaryTest {
public static void main(String[] args) throws Exception {
//case1
intToBinaryCase1(5);
//case2
String result = intToBinaryCase2(5);
System.out.println("case2: "+ result);
//case3
intToBinaryCase3(5);
//case4
System.out.println("case4(1): " + intToBinaryCase4(5,4));
System.out.println("case4(2): " + Integer.toString(5,2));
//case5
StringBuilder sb = new StringBuilder();
intToBinaryCase5(5, sb);
//case6
System.out.println("case6: " + intToBinaryCase6(5));
}
public static void intToBinaryCase1(int n) {
int bin[] = new int[16]; //change array size..
int i = 0;
while (n != 1) {
bin[i++] = n%2;
n = n/2;
}
bin[i] = n;
for( int j=i; j>=0; --j ){
System.out.println("case1: ["+j+"] = "+ bin[j]);
}
}
public static String intToBinaryCase2(int n) {
String s = "";
while (n > 0)
{
s = ( (n % 2 ) == 0 ? "0" : "1") + s;
//System.out.println("s:["+s+"]");
n = n / 2;
//System.out.println("n:["+n+"]");
}
return s;
}
public static void intToBinaryCase3(int n) {
int bin[] = new int[16]; //change array size..
int i = 0;
for( i=0; n!=1; i++ ) {
bin[i] = n%2;
n = n/2;
}
bin[i] = n;
for( int j=i; j>=0; --j ){
System.out.println("case3: ["+j+"] = "+ bin[j]);
}
}
public static String intToBinaryCase4(int n, int sq) throws Exception {
double pow = Math.pow(2, sq);
StringBuilder binary = new StringBuilder();
if (pow < n) {
throw new Exception("The length must be big from number.");
}
int shift = sq - 1;
for (; shift >= 0; shift--) {
int bit = (n >> shift) & 1;
if (bit == 1) {
binary.append("1");
} else {
binary.append("0");
}
}
return binary.toString();
}
private static void intToBinaryCase5(int n, StringBuilder sb) {
if (n > 0) {
sb.append(n % 2);
intToBinaryCase5(n >> 1, sb);
} else {
System.out.println("case5: "+sb.reverse().toString());
}
}
public static String intToBinaryCase6(int number){
StringBuilder sb = new StringBuilder();
if(number == 0)
return "0";
while(number>=1){
sb.append(number%2);
number = number / 2;
}
return sb.reverse().toString();
}
}
반응형
'Study & Edu > Algorithm' 카테고리의 다른 글
[Java] String to int, int to String 형변환 (1) | 2018.09.22 |
---|---|
[프로그래머스] 자연수 뒤집어 배열로 만들기 (3가지 방법) (0) | 2018.09.16 |
String to char/char[] 형변환, 혹은 그 반대로 형변환 (0) | 2018.09.11 |
[프로그래머스] 문자열 내 p와 y의 개수 (String to char array) (0) | 2018.09.11 |
[codility] 1 BinaryGap (0) | 2017.09.12 |