您的位置:首页 > 编程语言 > C语言/C++

[lintcode]二进制表示 ,Binary Representation

2017-04-10 23:04 330 查看
模拟题,很多细节需要注意,也有很多技巧,主要的想法是将数分成整数和小数两部分,分别转换成二进制。

(1).题目中没有说转换成二进制的整数部分会不会超过int_64,所以原则上应该考虑一下。

(2)判断double是否为0,需要设置一个极小值,否则程序可能不能停止。

(3)小数转二进制时,不能直接对乘二后的数进行下取整,需要判断一下和(1-eps)的距离。

(4)注意极端情况,顺便复习一下string 和stack的用法。

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
const double eps = 1e-6;
int max_ans = 200;
string ans;
int z = 0,zx = 0;
double x = 0.0, xxx = 0.0;
int len = n.length();
int64_t cnt = 10;
int flag = 0;

for(int i = 0; i < len; i++){
if(n[i] == '.'){
flag = 1;
continue;
}
if( flag == 0 ){
z = z * 10 + (n[i] -'0');
}
else{
x = x + (n[i] - '0')*1.0/cnt;
cnt *= 10;
}
}
xxx = x;
if( z == 0 ){
ans.append(1, '0');
}
else{
stack <char> st;
while(z != 0){
if(z&1 == true)
st.push('1');
else
st.push('0');
z = z >> 1;
}
while(!st.empty()){
ans.append(1, st.top());
st.pop();
}
}
if( abs(x) > eps ){
ans.append(1, '.');
int count = 0;
while(abs(x) > eps){

x = x * 2;
if( x > 1 - eps )
zx = 1;
else
zx = 0;
if(zx&1 == true){
ans.append(1, '1');
}
else
ans.append(1, '0');
count ++;
if(count > 32){

string err = "ERROR";
return err;
}
//cout<<x<<'$'<<floor(x)<<'$'<<(int)x<<'$'<<x-1<<endl;
//cout<<'$'<<zx<<endl;
x = x - zx;
//cout<<x<<endl;
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息