- 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;
}
};
博客围绕将十进制数(以字符串形式传入)转换为二进制字符串展开。若小数部分无法用最多32个字符精确表示,返回ERROR,并给出示例。还介绍了解法,先用atoi和atof得到整数和小数部分,再分别转换,同时给出转换时的注意点及原理。
383

被折叠的 条评论
为什么被折叠?



