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。