杭电oj —— 2051(十进制转二进制 Java有自带转换)

package com.demo2;
import java.util.Scanner;
/*
 * Give you a number on base ten,you should output it on base two.(0 < n < 1000)
 */
public class HDU_oj2051 {
	public static void main(String[] args) {
		Scanner sn = new Scanner(System.in);
		while(sn.hasNext()) {
			int n = sn.nextInt(); //十进制,将其转化为二进制
			System.out.println(compute(n));
		}
		sn.close();
	}
	public static String compute(int num) {
		int n = num;
		StringBuffer sb = new StringBuffer();
		while(n != 0) {
			int temp =n % 2; //模2 得到的是最后一位数
			sb.append(temp);
			n = n/2; //除以基数
		}
		return sb.reverse().toString();
	}
}
package com.demo2;

import java.util.Scanner;

public class HUD_oj2051_1 {
	public static void main(String[] args) {
		Scanner sn = new Scanner(System.in);
		while(sn.hasNext()) {
			int n = sn.nextInt(); //十进制,将其转化为二进制
			System.out.println(Integer.toBinaryString(n));
		}
		sn.close();
	}
}

猜你喜欢

转载自blog.csdn.net/LiLi_code/article/details/88551320