C++初学题

1、输入一个数n,求1到n的各阶乘之和

//计算每个数的阶乘
int Factorial(int n) {
	int ret = 1;
	for (int i = 1; i <= n; i++) {
		ret *= i;
	}
	return ret;
}
//把每个数的阶乘累加
int Factorial_Count(int n) {
	int ret = 0;
	for (int i = 1; i <= n; i++) {
		ret += Factorial(i);
	}
	return ret;
}
//一个for循环做
int Factorial(int n) {
	int ret = 1;
	int count = 0;
	for (int i = 1; i <= n; i++) {
		ret *= i;
		count += ret;
	}
	return count;
}

2、给定一个数组{ 7, 1, 3, 5, 1, 6, 8, 1, 3, 5, 7, 5, 6 },求任意给出范围内元素的和,如1~2,求和为1+3=4

class Solution {
public:
	Solution(int* arr, int len) {
		preSum = new int[len];
		preSum[0] = arr[0];
		for (int i = 1; i < len; i++) {
			preSum[i] = preSum[i - 1] + arr[i];
		}
	}

	int RangeSum2(int L, int R) {
		return L == 0 ? preSum[R] : (preSum[R] - preSum[L - 1]);
	}
public:
	int* preSum;
};


int main() {
	int arr[] = { 7, 1, 3, 5, 1, 6, 8, 1, 3, 5, 7, 5, 6 };
	int len = sizeof(arr) / sizeof(arr[0]);
	Solution s(arr, len);
	cout << s.RangeSum2(1, 2);
}

打印一个整数的32位二进制形式

void Print_Binary_32(int num) {
	for (int i = 31; i >= 0; i--) {
		cout << ((num & (1 << i)) == 0 ? "0" : "1");
	}
	cout << endl;
}
int main() {

	Print_Binary_32(1);  //00000000000000000000000000000001
	Print_Binary_32(2);  //00000000000000000000000000000010
	Print_Binary_32(8);  //00000000000000000000000000001000
	Print_Binary_32(-1); //11111111111111111111111111111111
	int a = INT32_MIN; 
	Print_Binary_32(a);	 //10000000000000000000000000000000
	int b = ~a + 1;//取相反数
	Print_Binary_32(b);  //10000000000000000000000000000000
	//相反数:各位取反再加1。 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值