Binary Representation

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 fractional part of the number can not be represented accurately in binary with at most 32 characters, return ERROR.

Example

For n = "3.72", return "ERROR".

For n = "3.5", return "11.1".

分析:

分成两个部分,整数部分用%和/,小数部分 *2 如果 <1 就为0,基数=基数;大于1,就为1,基数=基数-1 

比如:
0.6*2=1.2>0 那么就为1 基数=1.2-1=0.2

0.2*2=0.4<0 那么就为0,基数=0.4

0.4*2=0.8<0,那么就为0,基数=0.8

0.8*2=1.6>0 那么就为1,基数为1.6-1=0.6
:
:
:
:
所以5.6可以表示为:101.1001
 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        int count = 0;
19         while (decPart > 0.0 && count <= 32) {
20             double r = decPart * 2;
21             if (r >= 1.0) {
22                 decstr += '1';
23                 decPart = r - 1.0;
24             }else {
26                 decstr += '0';
27                 decPart = r;
28             }
29             count++;
30         }
31         
32         if (count > 32) return "ERROR";
33         return decstr.length() > 0? intstr + "." + decstr : intstr;
34     }
35 }

 

posted @ 2016-07-21 13:29  北叶青藤  阅读(250)  评论(0编辑  收藏  举报