• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Lintcode: 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 number can not be represented accurately in binary, print “ERROR”

Example
n = 3.72, return ERROR

n = 3.5, return 11.1

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 

 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 }

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

比如:

Input
 
0.5
Output
 
.1
Expected
 
0.1


Input
 
1.0
Output
 
1.
Expected
 
1

 

posted @ 2015-02-05 04:56  neverlandly  阅读(2023)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3