Lintcode 180: Binary Representation (二进制转换经典)

  1. Binary Representation
    中文English
    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
Example 1

Input: “3.72”
Output: “ERROR”
Explanation: (3.72)_{10} = (11.10111000010100011111\cdots)_2(3.72)
​10
​​ =(11.10111000010100011111⋯)
​2
​​ We can’t represent it in 32 characters.

Example 2

Input: “3.5”
OUtput: “11.1”
Explanation: (3.5)_{10}=(11.1)_2(3.5)
​10
​​ =(11.1)
​2
​​

解法1:思路。先用atoi和atof得到intV和fracV。然后分别对整数部分和小数部分进行二进制转换。
注意:
1)如果整数部分没有,记得加上"0"。
2)如果小数部分值为0,直接返回整数部分即可。
3)小数转二进制的原理是将小数部分乘2,若>1,则将二进制结果+1,然后将结果减去1继续,否则+0。
代码如下:

class Solution {
public:
    /**
     * @param n: Given a decimal number that is passed in as a string
     * @return: A string
     */
    string binaryRepresentation(string &n) {
        
        int strSize = n.size();
        
        if (strSize == 0) return "";
        
        int ptPos = n.find_first_of('.');
        
        int intV = 0;
        double fracV = 0.0;
        
        if (ptPos != string::npos) {
            intV = atoi(n.substr(0, ptPos).c_str());
            fracV = atof(n.substr(ptPos).c_str());
        } else {
            intV = atoi(n.c_str());
        }

        string intBinStr = "";
        while(intV) {
            if (intV & 0x1) { 
                intBinStr = '1' + intBinStr;
            } else {
                intBinStr = '0' + intBinStr;
            }
            intV >>= 1;
        }
        
        //don't forget.
        if (intBinStr == "") intBinStr = "0";
        
        if (fracV == 0) return intBinStr;
        
        string fracBinStr = "";
        while (fracV) {
            if (fracBinStr.size() > 32) return "ERROR";
            fracV *= 2;
            if (fracV >= 1) {
                fracBinStr += '1';
                fracV -= 1;
            } else {
                fracBinStr += '0';
            }
        }
        
        return intBinStr + '.' + fracBinStr;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值