java 我们将使用用于保存整数值(byte、short、int和long)的原语:

nhaq1z21  于 12个月前  发布在  Java
关注(0)|答案(5)|浏览(81)

给定一个输入整数,您必须确定哪些基元数据类型能够正确地存储该输入。
输入格式
第一行包含一个整数,表示测试用例的数量。每个测试用例都由一行整数组成,整数可以任意大或小。
输出格式
对于每个输入变量和适当的原语,必须确定给定的原语是否能够存储它。如果是,则打印:

! n can be fitted in:
! dataType

如果有多个合适的数据类型,则将每个类型打印在自己的行中,并按大小排序(即:byte<short<int<long)。如果数字不能存储在上述四个原语之一中,则打印行:

! n can't be fitted anywhere.

样本输入

5
-150
150000
1500000000
213333333333333333333333333333333333
-100000000000000

示例输出

-150 can be fitted in:
* short
* int
* long
150000 can be fitted in:
* int
* long
1500000000 can be fitted in:
* int
* long
213333333333333333333333333333333333 can't be fitted anywhere.
-100000000000000 can be fitted in:
* long

这是我写的代码。我也试过Long.MIN_VALUE和MAX_VALUE,在所有这些情况下都通过了,但这个代码没有通过所有的情况,我也试过大整数,但没有工作。

import java.util.*;
import java.io.*;
 

class Solution{
    public static void main(String []argh){
        
        Scanner sc = new Scanner(System.in);
        int t=sc.nextInt();

        for(int i=0;i<t;i++)
        { 
         try{
                long x = sc.nextLong();
                System.out.println(x+" can be fitted in:");
                if(x>=-128 && x<=127)System.out.println("* byte");
                if(x>=-32768 && x<=32767)System.out.println("* short");
                if(x>=-(int)Math.pow(2,31)&& x<=(int)Math.pow(2,31))System.out.println("* int");
                if(x>=-(long)Math.pow(2,63)&& x<=(long)Math.pow(2,63))System.out.println("* long");
            }
            else
            {
                System.out.println(sc.next()+" can't be fitted anywhere.");
            }

        }
    }
}
7cjasjjr

7cjasjjr1#

你有很多问题。
1.如果你读了一个long,你的“它不适合任何东西”怎么能触发呢?输入是213333333333333333333333333333333333,您将其读取为long,这会立即失败并引发异常。解决这个问题并不容易-基本上需要完全重写。你不能把你的输入作为一个数字(因为没有比long更大的东西了)。它必须是一个字符串,因此,要检查“它是否适合”,你不能做>=-128,你必须尝试将任何字符串解析成一个字节,看看它是否有效。

  1. Math.pow用于double(即不准确的)数学,并且不能正确完成工作。如果你想要“最小的整数”,那应该是Integer.MIN_VALUEInteger.MAX_VALUE,而不是Math.pow(2,31),这实际上不是你想要的。因为复杂的-double是不准确的,这是过于简单的原因,而Math.pow做的是双重数学。
    大多数情况下,第2点是无关紧要的,因为第1点说,这整个方法不可能首先工作。
    这个问题比乍看上去要难一些。提示:你想要.next()(不是.nextLong()),你想知道如何捕获异常,你想 * 尝试 * 使用例如解析字符串。Byte.parseByteLong.parseLong等等。如果它工作,打印该数据类型。如果它失败了(发生了一个异常,你必须捕获它),不要打印它。它看起来一点也不像你写的。这不是你的错--这种方法很好,直到你遇到一个讨厌的问题,你应该能够阅读如此之大的数字,他们甚至不适合在一个长。
cyej8jka

cyej8jka2#

让JDK通过让Java的Number类尝试解析输入来完成繁重的工作:

String x = sc.nextLine();
System.out.println(x + " can be fitted in:");
if (canFit(x, Byte::parseByte)) System.out.println("* byte");
if (canFit(x, Short::parseShort)) System.out.println("* short");
if (canFit(x, Integer::parseInt)) System.out.println("* int");
if (canFit(x, Long::parseLong)) System.out.println("* long");
if (!canFit(x, Byte::parseByte) &&
    !canFit(x, Short::parseShort) &&
    !canFit(x, Integer::parseInt) &&
    !canFit(x, Long::parseLong)) System.out.println("can't be fitted anywhere.");

并定义此方法:

static boolean canFit(String input, Consumer<String> parser) {
    try {
        parser.accept(input);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}
rn0zuynd

rn0zuynd3#

你让你的生活变得不必要的困难。您已经在使用Scanner,它可以为您执行所有必要的检查。你只需要问:

int t = sc.nextInt();
for(int i = 0; i < t; i++) {

    boolean fitsByte = sc.hasNextByte(), fitsShort = sc.hasNextShort(),
        fitsInt = sc.hasNextInt(), fitsLong = sc.hasNextLong();

    System.out.print(sc.next());

    if(!fitsLong) System.out.println(" can't be fitted anywhere.");
    else {
        System.out.println(" can be fitted in:");
        if(fitsByte) System.out.println("* byte");
        if(fitsShort) System.out.println("* short");
        if(fitsInt) System.out.println("* int");
        System.out.println("* long");
    }
}

请记住,您必须在next()之前调用hasNext…(),以查询下一个元素的属性。
请注意,扩展到其他类型是多么容易:

int t = sc.nextInt();
for(int i = 0; i < t; i++) {

    boolean fitsByte = sc.hasNextByte(), fitsShort = sc.hasNextShort(),
        fitsInt = sc.hasNextInt(), fitsLong = sc.hasNextLong(),
        fitsBig = sc.hasNextBigInteger();

    System.out.print(sc.next());

    if(!fitsBig) System.out.println(" can't be fitted anywhere.");
    else {
        System.out.println(" can be fitted in:");
        if(fitsByte) System.out.println("* byte");
        if(fitsShort) System.out.println("* short");
        if(fitsInt) System.out.println("* int");
        if(fitsLong) System.out.println("* long");
        System.out.println("* BigInteger");
    }
}

(An如果输入包含分数或根本不是数字,则它将不适合BigInteger

guicsvcw

guicsvcw4#

import java.util.*;
import java.io.*;
 
class Solution{
    public static void main(String []argh){
        
        Scanner sc = new Scanner(System.in);
        int t=sc.nextInt();

        for(int i=0;i<t;i++)
        { 
           try{
              long x= sc.nextLong();
                System.out.println(x+" can be fitted in:");

                if(x>=-128 && x<=127)System.out.println("* byte");

                if(x>=-32768 && x<=32767)System.out.println("* short");

                if(x>=-Integer.MIN_VALUE&& x<= 
                       Integer.MAX_VALUE)System.out.println("* int");

                if(x>=-Long.MIN_VALUE&& x<= 
                       Long.MAX_VALUE)System.out.println("* long");

            }
            catch(Exception e){
                System.out.println(sc.next()+" can't be fitted anywhere.");
            }    
        }           
    }
}

谢谢你们所有人的帮助我,你的答案教了我很多新的东西.谢谢你们所有人对我的青睐,现在我得到了满足我的条件的代码,你们所有人也给了我一个代码相同的输出,代码也是正确的,但我想告诉你我的答案,

ubbxdtey

ubbxdtey5#

使用 BigInteger 类来计算数字。
此外,利用 * 静态数据结构 * 为每个 * 原始数据类型 * 提供范围值。

import static java.lang.String.valueOf;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Util {
    static List<Class<?>> fit(BigInteger i) {
        List<Class<?>> l = new ArrayList<>();
        for (Map.Entry<Class<?>, Range> e : Range.map.entrySet())
            if (e.getValue().withinBounds(i)) l.add(e.getKey());
        return l;
    }

    static class Range {
        static Map<Class<?>, Range> map = new LinkedHashMap<>() {{
            put(byte.class, Range.of(byte.class));
            put(short.class, Range.of(short.class));
            put(char.class, Range.of(char.class));
            put(int.class, Range.of(int.class));
            put(long.class, Range.of(long.class));
        }};
        BigInteger minimum, maximum;

        private Range(BigInteger minimum, BigInteger maximum) {
            this.minimum = minimum;
            this.maximum = maximum;
        }

        boolean withinBounds(BigInteger x) {
            return x.compareTo(minimum) >= 0 && x.compareTo(maximum) <= 0;
        }

        static Range of(Class<?> c) {
            return new Range(min(c), max(c));
        }

        private static BigInteger min(Class<?> c) {
            String s = null;
            if (c == byte.class) s = valueOf(Byte.MIN_VALUE);
            else if (c == short.class) s = valueOf(Short.MIN_VALUE);
            else if (c == char.class) s = valueOf((int) Character.MIN_VALUE);
            else if (c == int.class) s = valueOf(Integer.MIN_VALUE);
            else if (c == long.class) s = valueOf(Long.MIN_VALUE);
            return s != null ? new BigInteger(s) : null;
        }

        private static BigInteger max(Class<?> c) {
            String s = null;
            if (c == byte.class) s = valueOf(Byte.MAX_VALUE);
            else if (c == short.class) s = valueOf(Short.MAX_VALUE);
            else if (c == char.class) s = valueOf((int) Character.MAX_VALUE);
            else if (c == int.class) s = valueOf(Integer.MAX_VALUE);
            else if (c == long.class) s = valueOf(Long.MAX_VALUE);
            return s != null ? new BigInteger(s) : null;
        }
    }
}

下面是一个示例用法。

String s = "5 -150 150000 1500000000 213333333333333333333333333333333333 -100000000000000";
Scanner sc = new Scanner(s);
BigInteger x;
while (sc.hasNextBigInteger())
    System.out.printf("%s%n%s%n%n", x = sc.nextBigInteger(), Util.fit(x));

输出

5
[byte, short, char, int, long]

-150
[short, int, long]

150000
[int, long]

1500000000
[int, long]

213333333333333333333333333333333333
[]

-100000000000000
[long]

相关问题