第四章 课外练习3
第一题
输入一个整数,计算其二进制中1的个数。例如输入7,输出3.(7 = 0000 0000 0000 0000 0000 0000 0000 0111, 有3个1)
代码
#include<iostream>
using namespace std;
int main(){
int n;
int sum = 0;
cin >> n;
for (int i = 0; i < 32; i++) {
sum += n % 2;
n /= 2;
}
cout << sum;
return 0;
}
第二题:输入一个整数。输出其8位16进制值,其中字母用大写。例如输入10,输出0000000A
#include<iostream>
using namespace std;
int main(){
int num;
cin >> num;
int arr[8];
for (int i = 0; i < 8; i++) {
arr[i] = num % 16;
num /= 16;
}
for (int j = 7; j >= 0; j--) {
if (arr[j] < 10) cout << arr[j];
else {
char ch = 'A';
cout << char(ch + arr[j] - 10);
}
}
system("pause");
return 0;
}
第三题:编程输出ABCD的全排列,每行输出5个,中间以空格分开。
代码一:
#include<iostream>
using namespace std;
int main(){
char ch[5] = "ABCD";
int n = 0;
for (int a = 0; a < 4; a++) {
for (int b = 0; b < 4; b++) {
for (int c = 0; c < 4; c++) {
for (int d = 0; d < 4; d++) {
if (a != b && a != c && a != d && b != c && b != d && c != d) {
cout << ch[a] << ch[b] << ch[c] << ch[d] << " ";
n++;
if (n % 4 == 0) cout << endl;
}
}
}
}
}
return 0;
}
代码二:时间复杂度是低于代码一的。建议使用代码二。
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
char ch[5] = "ABCD";
int n = 0;
for (int i = 0; i < 24; i++) {
for (int j = 0; j < 4; j++) cout << ch[j];
cout << " ";
if ((i + 1) % 4 == 0) cout << endl;
next_permutation(ch, ch + 4);
}
system("pause");
return 0;
}
5601

被折叠的 条评论
为什么被折叠?



