PS: 程序為cpp代碼,最重要理解操作。
方法一: n進制方法,也可以解決轉換為其他進制問題。
/*將整數轉化為二進制的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;
}
方法三: 遞歸輸出轉換二進制
/*遞歸轉換二進制*/
void convert(int n) {
int a;
a = n % 2;
n = n >> 1;
if (n == 0)
return;
else
convert(n);
cout << a; // 01逐個輸出
}
方法四:位運算轉換二進制
/*位運算轉換二進制*/
void convert(int n) {
for (int = 31; i >= 0; i--) { // 32位,逐步與1做與運算
cout << (n >> i) & 1;
}
}
方法五:使用bitset 轉換二進制
void convert(int n) {
cout << bitset<sizeof(int) * 8>(n) << endl;
}