【CodeForces】[66A]Petya and Java

Problem Description

Loading...

Problem Analysis

Determine the data type of a number

Except for BigInteger, all others can be determined directly
So the main task is to determine whether it is BigInteger
This can be based on the number of digits
Then we only need to handle cases where the digit count equals that of the boundary value

The rest is some small tricks

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<stdio.h>
#include<string.h>
int l;
char s[120];
char res[5][11]= {"byte","short","int","long","BigInteger"};
bool cmp() {
	int x=(s[0]=='-'?1:0);
	if(l>19+x)
		return true;
	if(l<19+x)
		return false;
	char bg[20]="9223372036854775807";
	if(x)
		bg[18]='8';
	for(int i=x; i<l; i++) {
		if(s[i]>bg[i-x])
			return true;
		if(s[i]<bg[i-x])
			return false;
	}
	return false;
}
int judge() {
	if(cmp())
		return 4;
	else {
		__int64 sum=0;
		int i=(s[0]=='-'?1:0);
		for(; i<l; i++)
			sum=sum*10+s[i]-'0';
		if(s[0]=='-')
			sum--;
		if(sum<128)
			return 0;
		if(sum<32768)
			return 1;
		if(sum<=2147483647)
			return 2;
		else
			return 3;
	}
}
int main() {
	while(scanf("%s",s)!=EOF) {
		l=strlen(s);
		printf("%s\n",res[judge()]);
	}
	return 0;
}

Problem link:【CodeForces】[66A]Petya and Java

Statement:
Given a number, output its data type

  • 128~127 is byte
  • 32768~32767 is short
  • 2147483648~2147483647 is int
  • 9223372036854775808~9223372036854775807 is long

All others are BigInteger

Solution process:
Because the number of digits is large
it can be read as a string

Except for BigInteger, all others are within the range of __int64
So if we can determine that the number is in - 9223372036854775808~9223372036854775807
then it can be converted to a number, stored in __int64, and further range-checked

So the main task is to determine whether it is BigInteger
This can be preliminarily determined by the number of digits
It can be seen that
Positive numbers with a string length greater than 19 (s[0]!=’-’) and negative numbers with a length greater than 20 (s[0]==’-’)
must be BigInteger
Positive numbers with a string length less than 19 (s[0]!=’-’) and negative numbers with a length less than 20 (s[0]==’-’)
must not be BigInteger
So we only need to handle the equality case

Then we can create a string “9223372036854775807”
and compare it with the string to make the determination

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...