题解:P12681 【MX-J15-T1】叉叉学习数据类型

· · 题解

题意

给一个整数 n,求这个数在哪一个数据类型的取值范围内。

思路

由于范围中给出 |n| \le 10^{100},因此需要用高精度存数字。

随后,将 n 和各个数据类型的范围边界比较,若在范围内则这个数据类型可以存储 n

以下给出各数据类型的范围:

Code

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
struct bignum{
    int num[105], len, type;
    bignum(){
        len = 1; // 长度
        type = 0; // 正负,初始为 0
    }
    int &operator[](int i){
        return num[i];
    } // 定义 a[i] = a.num[i] 以便访问
    void strnum(string str){ // 字符串转高精度
        if(str == "0"){ // 为 0
            len = 1;
            type = 0;
            num[1] = 0;
            return ;
        }
        if(str.front() == '-') type = -1; // 有负号,正负改为负数
        else type = 1; // 没负号,为正数
        for(int i = 0;i < str.length();i++){
            if(!isdigit(str[i])) continue;
            num[str.length() - i] = str[i] - '0';
        } // 存储数字
        len = str.length();
        if(type == -1) len--;
        return ;
    }
    friend bool operator >(bignum a, bignum b){ // 定义大于号
        if(a.type < b.type) return false;
        if(a.type > b.type) return true;
        if(a.type == b.type && a.type == 0) return false;
        if((a.len > b.len && a.type == 1) || (a.len < b.len && a.type == -1)) return true;
        if((a.len < b.len && a.type == 1) || (a.len > b.len && a.type == -1)) return false;
        for(int i = a.len;i >= 1;i--){
            if((a[i] < b[i] && a.type == 1) || (a[i] > b[i] && a.type == -1)) return false;
            if((a[i] > b[i] && a.type == 1) || (a[i] < b[i] && a.type == -1)) return true;
        }
        return false;
    }
};
bignum retnum(string str){
    bignum res;
    res.strnum(str);
    return res;
} // 将字符串转换为高精度数
bignum n;
string inpn;
int main()
{
    cin >> inpn;
    n.strnum(inpn);
    // 正常的分支结构,开始比较
    if(n > retnum("-2147483649") && retnum("2147483648") > n) puts("int");
    if(n > retnum("-1") && retnum("4294967296") > n) puts("unsigned int");
    if(n > retnum("-9223372036854775809") && retnum("9223372036854775808") > n) puts("long long");
    if(n > retnum("-1") && retnum("18446744073709551616") > n) puts("unsigned long long");
    puts("string"); // 任何数字都可用 string 存储,因此最后输出 string
    return 0; // 结束 (。・ω・。)
}