Lintcode: Binary Representation

王朝学院·作者佚名  2016-05-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

Lintcode: Binary RePResentationGiven a (decimal - e g 3.72) number that is passed in as a string,return the binary representation that is passed in as a string.If the number can not be represented accurately in binary, print “ERROR”Examplen = 3.72, return ERRORn = 3.5, return 11.1

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

1. use%2to 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

1 public class Solution { 2 /** 3 *@param n: Given a decimal number that is passed in as a string 4 *@return: A string 5 */ 6 public String binaryRepresentation(String n) { 7 int intPart = Integer.parseInt(n.substring(0, n.indexOf('.'))); 8 double decPart = Double.parseDouble(n.substring(n.indexOf('.'))); 9 String intstr = "";10 String decstr = "";11 12 if (intPart == 0) intstr += '0';13 while (intPart > 0) {14 int c = intPart % 2;15 intstr = c + intstr;16 intPart = intPart / 2;17 }18 19 while (decPart > 0.0) {20 if (decstr.length() > 32) return "ERROR";21 double r = decPart * 2;22 if (r >= 1.0) {23 decstr += '1';24 decPart = r - 1.0;25 }26 else {27 decstr += '0';28 decPart = r;29 }30 }31 return decstr.length() > 0? intstr + "." + decstr : intstr;32 }33 }

这道题还有一些细节要处理,我之前忽略了

比如:

Input0.5

Output.1

Expected0.1

Input1.0

Output1.

Expected1

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航