public static String ToBinaryString(int scanStr){
final String FINAL_ONESTRING = "11111111111111111111111111111111";
final String FINAL_MIN_VALUE = "10000000000000000000000000000000";
switch (scanStr) {
case 0 : return "0";
case 1 : return "1";
case -1 : return FINAL_ONESTRING;
case Integer.MIN_VALUE : return FINAL_MIN_VALUE;
}
boolean fushuFlag = scanStr < 0;
if (fushuFlag)
scanStr = 0 - scanStr;
StringBuilder sb = new StringBuilder();//默认16字符
while (scanStr != 1){
int yushu = scanStr % 2;
scanStr = scanStr >> 1;
sb = sb.append(yushu);
}
sb = sb.append(1);//补首位
if (fushuFlag){
int sblength = sb.length();
for(int i = 0; i< sblength;i++){//对正数进行取反操作
char charAt = sb.charAt(i);
if(charAt == '1')
sb.setCharAt(i, '0');
else
sb.setCharAt(i, '1');
}
if(sb.charAt(0) == '1'){//首位是1 进行加法计算
int index = sb.indexOf("0",1);//一个值为0的offset
sb.setCharAt(index, '1');//进位计算
for(int i = 0; i < index; i++)
sb.setCharAt(i, '0');//index前面的值全部置0
}else{
sb.setCharAt(0, '1');
}
return FINAL_ONESTRING.substring(sb.length()) + sb.reverse().toString();
}
return sb.reverse().toString();
}//
long flag1 = System.currentTimeMillis();
for(int i = 0; i<10000000; i++){
Integer.toBinaryString(154);
}
long flag2 = System.currentTimeMillis();
for(int i = 0; i<10000000; i++){
ToBinaryString(154);
}
long flag3 = System.currentTimeMillis();
System.out.println(flag2 - flag1);//测试input:154 执行1000W次 耗时 15672
System.out.println(flag3 - flag2);//测试input:154 执行1000W次 耗时 37781