PS: 程序爲cpp代碼,最重要理解操做。spa
方法一: n進制方法,也能夠解決轉換爲其餘進制問題。blog
/*將整數轉化爲二進制的string 輸出*/
string convert(int num) {
string res = "";
if (num == 0) return "0";
int val = num;
num = abs(num);
while (num) {
res.insert(0, to_string(num % 2));
num /= 2;
}
if (val < 0) res.insert(0, "-");
return res;
}
方法二: 使用容器轉換遞歸
/*使用vector進行存儲*/
vector<int> convert(int n) {
int temp;
temp = n;
vector<int> res;
while (temp !=0) {
res.push_back(temp % 2);
temp = temp >> 1;
}
return res;
}
方法三: 遞歸輸出轉換二進制string
/*遞歸轉換二進制*/
void convert(int n) {
int a;
a = n % 2;
n = n >> 1;
if (n == 0)
return;
else
convert(n);
cout << a; // 01逐個輸出
}
方法四:位運算轉換二進制it
/*位運算轉換二進制*/
void convert(int n) {
for (int = 31; i >= 0; i--) { // 32位,逐步與1作與運算
cout << (n >> i) & 1;
}
}
方法五:使用bitset 轉換二進制class
void convert(int n) {
cout << bitset<sizeof(int) * 8>(n) << endl;
}