Given 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.5Output
.1Expected
0.1Input
1.0Output
1.Expected
1
新闻热点
疑难解答