第四章 课外练习3

第四章 课外练习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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值