二进制表示-LintCode
2017-08-24 17:10
253 查看
给定一个数将其转换为二进制(均用字符串表示),如果这个数的小数部分不能在 32 个字符之内来精确地表示,则返回 “ERROR”。
样例:
n = “3.72”, 返回 “ERROR”.
n = “3.5”, 返回 “11.1”.
样例:
n = “3.72”, 返回 “ERROR”.
n = “3.5”, 返回 “11.1”.
#ifndef C180_H #define C180_H #include<iostream> #include<string> using namespace std; class Solution { public: /** *@param n: Given a decimal number that is passed in as a string *@return: A string */ string binaryRepresentation(string n) { // wirte your code here if (n.empty()) return NULL; int len = n.size(); int pos = 0; for (int i = 0; i < len; ++i) { if (n[i] == '.') { pos = i; break; } } string Integer = n.substr(0,pos); string Decimal = n.substr(pos + 1, len - 1 - pos); int size = Decimal.size(); long long intNum = stoll(Integer); long long DecNum = stoll(Decimal); double num = DecNum; for (int j = 1; j <= size; ++j) { num /= 10; } int count = 0; string sum; while (num != 0) { count++; num *= 2; if (num >= 1) { num -= 1; sum += "1"; } else { sum += "0"; } } if (count > 32) return "ERROR"; else { string str; if (intNum == 0) str= "0"; for (int i = intNum; i; i = i / 2) { str += (i % 2 ? "1" : "0"); } reverse(str.begin(), str.end()); if (sum.empty()) return str; return str + "." + sum; } } }; #endif
相关文章推荐
- LintCode 二进制表示
- LintCode : 二进制表示
- LintCode 180-二进制表示
- [lintcode]二进制表示 ,Binary Representation
- lintcode 二进制求和 给定两个二进制字符串,返回他们的和(用二进制表示)。
- LintCode : 二进制表示
- 负数如何用二进制表示
- 浮点数的二进制表示
- 负数的二进制表示与转换
- 二进制表示
- 负数的二进制表示
- 浮点数的二进制表示
- lintcode--二进制时间
- 计算一个十进制数的二进制表示有多少位1
- 统计一个自然数的二进制表示形式中有多少个1
- 编程之美2.4 以二进制表示的1-N中1的数目
- 浮点数的二进制表示
- 二进制位,字节,字长计算机内表示,及二进制、八进制、十六进制
- 小数 二进制 的 表示与转换
- 位操作:一个整数的二进制表示中 有多少个1?