#include#include "algorithm" #include "cmath"#include "string"#include using namespace std;int main(){ int sav[8]={ 1,2,4,8,16,32,64,128};//2^n事先存储 int er[8]={ 0};//存储二进制01 int phigh=7; int cur=0; int sum=100; while(phigh>=0){ cur+=sav[phigh]; if(cur>sum){ cur-=sav[phigh]; //cout<<"情况1"< <
也可以不用事先存储:(只适合正整数求补码)
#include#include "algorithm" #include "cmath"#include "string"#include #include "bitset"using namespace std;int main(){//如果只是输出就不用事先存储了 int phigh=7; int cur=0; int num=0;//位数 int sum=100; while(phigh>=0){ cur+=pow(2,phigh); if(cur>sum){ cout<<0;num++; cur-=pow(2,phigh); phigh--;//之前忽略了这个 } else if(cur==sum){ cout<<1;num++; break; } else{ cout<<1;num++; phigh--; }} for(int i=1;i<=8-num;i++){ //默认8位 cout<<0; }cout<
常规解法:(只适合正整数求补码)
#include#include "algorithm" #include "cmath"#include "string"#include using namespace std;int main(){int sum=100;vector res; while(sum){res.push_back(sum%2);sum=sum/2; }reverse(res.begin(),res.end());for(vector ::iterator it=res.begin();it!=res.end();it++)cout<<*it; }
库函数://正负数都可以
#include#include #include using namespace std;int main(){ bitset<8> t=-125; cout<