zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Linux命令: ls -l显示文件和目录的详细资料
    Linux命令: ls -F
    Linux命令: pwd显示工作路径
    Linux命令: cd /home 进入'/home'目录
    Linux命令: cd ../.. 返回上两级目录
    Linux命令: cd
    boost::mpl::eval_if的使用方法
    【block第四篇】实现
    Android中pendingIntent的深入理解
    hdu 1565 方格取数(1)(状态压缩dp)
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4273813.html
Copyright © 2011-2022 走看看