牛课题15-牛牛与二进制
题目描述
牛牛想把一个数n转化为八位的二进制数,只不过牛牛不知道该怎么做,所以他想请你帮忙。
给定一个数n,返回将这个数转化为八位的二进制数(不足八位,往前补0)。
示例1
输入
1
返回值
“00000001”
①运用短除法把余数存起来,知道除数为0 时结束,再把所得字符串填充成8位再倒叙返回,即所得结果
public String tranBinary (int n) {
// write code here
String result = "";
//求二进制数
while(n != 0){
result += n % 2;
n = n / 2;
}
//补位
while (result.length() < 8)
result += 0;
result = new StringBuilder(result).reverse().toString();//倒序输出
return result;
}
②运用Java类库中的方法
String s = Integer.toBinaryString(n);
把n转成二进制,以字符串的形式返回
String.format("%08d",Integer.valueOf(s));
format"0"表示空位补0,8表示返回八位,d十进制
public String tranBinary (int n) {
// write code here
String s = Integer.toBinaryString(n);
return String.format("%08d",Integer.valueOf(s));//转换成八位输出,空位添0
}
③与②的区别在于输出格式的不同
*/
public String tranBinary (int n) {
// write code here
String s = Integer.toBinaryString(n);
String str = "00000000";
return str.substring(s.length()) + s;
}
}