unsigned long long类型与long long类型

时间:2022-09-15 18:25:49

最近做题的时候,经常遇到范围是2^63,取模2^64的这种题目。遇到这种限制条件时就要想到用unsigned long long类型。

可以简洁地声明为typedef unsigned long long ull。这样,如果ull类型的整数溢出了,就相当于取模2^64了。因为ull的范围是[0,2^64-1]。

而ll的范围是[-2^63,2^63-1],因为有符号的第63位表示“正负”而不表示数值

下面给出几组对比程序来加深印象:

(1)

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;

int main()
{
ll a = ~0LL >> 1;
ull b = ~0LL >> 1;
cout << a << ' ' << b << endl;
}
/*
输出结果:
-1 18446744073709551615
*/

 (2)

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;

int main()
{
ll a = (1LL << 63) - 1;
ull b = (1LL << 63) - 1;
cout << a << ' ' << b << endl;
cout << a + 1 << ' ' << b + 1 << endl;
}
/*
输出结果:
9223372036854775807 9223372036854775807
-9223372036854775808 9223372036854775808
*/

(3)

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;

int main()
{
ull a = (1LL << 64) - 1;
cout << a << ' ' << a + 1 << endl;
}
/*
输出结果:
18446744073709551615 0
*/