Zhuohong Gu Zhuohong Gu - 2 months ago 18
Java Question

Algorithm of number conversion?

public static String DeciToBin(int i)
{
String zero="0";
String one="1";
String str = "";
if(i==0)
{
return zero;
}
if(i==1)
{
return one;
}
for(;i<2;i/=2)
{
if(i%2==1)
{
str= one+str;
}
if(i%2==0)
{
str=zero+str;
}
}
return str;
}


It turned out nothing when i is bigger than 1. There's no error or caution in these lines. What did I miss?

Answer

You need to test whether i>0 or not not stop if you get a number of 2 or more.

You can simplify this a lot.

public static String deciToBin(int i) {
    String str = "";
    do {
        str = (i & 1) + str;
        i >>>= 1;
    } while (i != 0);
    return str;
}

Even better would be to use StringBuilder

public static String deciToBin(int i) {
    StringBuilder str = new StringBuilder();
    do {
        str.append(i & 1);
        i >>>= 1;
    } while (i != 0);
    return str.reverse().toString();
}