日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Cracking the Coding Interview 5.2

發(fā)布時(shí)間:2023/12/13 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Cracking the Coding Interview 5.2 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Given a(decimal -e.g. 3.72)number that is passed in as a string, print the binary representation. If the number can not be represented accurately in binary, print "ERROR"

?

整數(shù)部分:

? ? 對2取余,然后向右移動一位,重復(fù)直到整數(shù)部分變?yōu)?

小數(shù)部分:

? ? 乘以2,看結(jié)果是否大于1,大于1則2^-1位上位1,否則為0。如果大于1,將結(jié)果減1再乘以2,否則直接乘以2,繼續(xù)判斷,直到小數(shù)部分超過32位,返回ERROR

? ? 例如:0.75d = 0.11b,乘以2實(shí)際上相當(dāng)于左移,結(jié)果大于1,則說明2^-1位上是1,然后減1,繼續(xù)乘以2,結(jié)果等于1,說明2^-2上是1,且后面沒有小數(shù)了。

#include<iostream> #include<string> #include<stdlib.h> using namespace std;string func(const string &str) {string strInt;string strDou;string::size_type idx = str.find('.'); if(idx == string::npos){strInt = str;}else{strInt = str.substr(0,idx);strDou = str.substr(idx);}int intPart = atoi(strInt.c_str());double douPart;if(!strDou.empty()){douPart = atof(strDou.c_str());}else{douPart = 0.0;}string strIntB,strDouB;while(intPart!=0){if((intPart&1)>0){strIntB = '1'+strIntB;}else{strIntB = '0'+strIntB;}intPart=intPart>>1;}while(!(douPart>-10e-15 && douPart<10e-15)){if(douPart*2>1){strDouB = '1'+strDouB;douPart = douPart*2-1;}else if((douPart*2-1)>-10e-15 && (douPart*2-1)<10e-15){strDouB = '1'+strDouB;break;}else{strDouB = '0'+strDouB;}if(strDouB.size()>32){return "ERROR";}}if(strDouB.empty()){return strIntB;}else{return (strIntB+'.'+strDouB);} }int main() {string str("3.75");cout<<func(str)<<endl;return 0; }

?

轉(zhuǎn)載于:https://www.cnblogs.com/johnsblog/p/3923016.html

總結(jié)

以上是生活随笔為你收集整理的Cracking the Coding Interview 5.2的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。