牛牛想把一个数n转化为八位的二进制数,只不过牛牛不知道该怎么做,所以他想请你帮忙。
给定一个数n,返回将这个数转化为八位的二进制数(不足八位,往前补0)。
为什么没人做这个题
func tranBinary( n int ) string { b:=fmt.Sprintf("%08b",n) return b }
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 给定一个数n,返回将这个数转化为八位的二进制数(不足八位,往前补0)。 * @param n int整型 代表题目中的n * @return string字符串 */ string tranBinary(int n) { // write code here string s="00000000"; int i=7; while(n!=0){ s[i]=n%2+'0'; n/=2; i--; } return s; } };
public String tranBinary (int n) { String s = Integer.toBinaryString(n); return String.format("%08d", Integer.valueOf(s)); }
public String tranBinary(int n) { StringBuilder res = new StringBuilder(Integer.toString(n, 2)); while (res.length() != 8) { res.insert(0, "0"); } return res.toString(); }
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 给定一个数n,返回将这个数转化为八位的二进制数(不足八位,往前补0)。 * @param n int整型 代表题目中的n * @return string字符串 */ public String tranBinary (int n) { // write code here String str = Integer.toBinaryString(n); String s = "00000000"; return s.substring(str.length()).concat(str); } }