C++中\(int\)和\(long\ long\)特别容易被忽略的点,在做乘法的时候即使单个变量在\(int\)范围内,如果乘积超了\(int\),也需要将乘数定义为\(long\ long\) 否则会出错!
#include <bits/stdc++.h>
using namespace std;
int main(){
int i = 100000000;
long long j = 100000000;
cout << i*i << " " << sizeof(i*i) << " " << (long long)i*i << " " << sizeof((long long)i*i) << " " << i << endl;
cout << j*j << " " << sizeof(j*j) << " " << int(j*j) << " " << sizeof(int(j*j)) << " " << j << endl;
return 0;
豆爸踩过的坑:
洛谷P2415
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 110;
LL a[N];
int n;
LL res;
int main() {
//录入进来,终止条件是CTRL+D,最起码在CLion里是这样的.DevC++里试试ctrl+z
while (cin >> a[++n]);
//找规律
元素个数n=2
[2][3]
[2,3]
2出现2次,3出现2次。就元素都出现2^1次。
2,3,4
元素个数n=3
[2][3][4]
[2,3][2,4][3,4]
[2,3,4]
2出现4次,3出现4次,4出现4次,就元素都出现2^2次。
发现规律:
任意元素出现2^(n-1)次!
//暴力版本
//for (int i = 1; i <= n; i++)res += a[i] * pow(2, n - 1);
//位运算优化版本
//for (int i = 1; i <= n; i++)res += (LL)a[i] * (1 << n - 1);
for (int i = 1; i <= n; i++)res += a[i] * (1 << n - 1);
C++中int和long long特别容易被忽略的点,在做乘法的时候即使单个变量在int范围内,如果乘积超了int,
也需要将乘数定义为longlong 否则会出错
cout << res << endl;
return 0;