[CrackCode] 5.2 Print the binary representation

Given a (decimal - e g 3.72) number that is passed in as a string, print the binary rep-resentation If the number can not be represented accurately in binary, print “ERROR” 

============

Analysis:

This is a typical example of how to transform a decimal number to binary number.  Basic idea is to divide the decimal number into 2 parts, i.e., the int part (e.g. 3), and the decimal part (e.g. 0.72).

For int part, similar approach of extracting numbers from int:

1. use %2 to get each digit from lowest bit to highest bit.

2. int right shift 1 position (=>>1).

3. construct the binary number (always add to the higher position of the current binary number)

Please refer to the code below for the process above.

For decimal part, use *2 approach.  For example:

int n = 0.75

n*2 = 1.5

Therefore, the first digit of binary number after '.' is 1 (i.e. 0.1).  After constructed the first digit, n= n*2-1 (remaining number would actually be *(2^2) before calculating the next digit)

When the remaining number ==1, the decimal number has been successfully transformed to binary number.  Otherwise, the decimal number could not be transform to binary number.

public class Answer {
	public static String printBinary(String str){
		int intPart = Integer.parseInt(str.substring(0,str.indexOf('.')));
		double decPart = Double.parseDouble(str.substring(str.indexOf('.')));
		
		// transform int part to binary
		String int_string = "";
		while(intPart>0){
			int r = intPart%2;
			intPart>>=1;
			int_string = r+int_string;
		}
		
		// transform dec part to binary
		StringBuffer dec_string=new StringBuffer();
		while(decPart>0){
			if(dec_string.length()>32) return "ERROR!";
			
			if(decPart == 1){// exit
				dec_string.append((int)decPart);
				break;
			}
			
			double r = decPart*2;
			if(r>=1){
				dec_string.append("1");
				decPart = r-1;
			}
			else{
				dec_string.append("0");
				decPart = r;
			}
		}
		return (int_string + "." + dec_string);
	}
	
	public static void main(String[] args) {
		String n = "19.25";
		String bs = printBinary(n);
		System.out.println(bs);
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值