java怎样实现判断一个最高达1000位数字的整数是不是3的倍数。

2025-03-15 19:34:04
推荐回答(2个)
回答(1):

能被3整除的数的特征:各个数位上的数相加之和必定为3的倍数。


import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        try (Scanner sc = new Scanner(System.in))
        {
            while (sc.hasNext())
            {
                String num = sc.next();
                int sum = 0;
                for (int i = 0; i < num.length(); i++)
                    sum += Integer.parseInt("" + num.charAt(i));
                System.out.println(sum % 3 == 0 ? "yes" : "no");
            }
        }
    }
}

如果使用BigInteger也行,只不过OJ平台可能对时空复杂度有要求,容易过不去。

import java.math.BigInteger;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        final BigInteger bigThree = new BigInteger("3");
        try (Scanner sc = new Scanner(System.in))
        {
            while (sc.hasNextBigInteger())
            {
                BigInteger num = sc.nextBigInteger();
                System.out.println(num.mod(bigThree).equals(BigInteger.ZERO) ? "yes" : "no");
            }
        }
    }
}

运行结果不变。

回答(2):

java编程 从控制台上输入一个数字用三目运算符:判断它是否是3的倍数的程序如下:

import java.util.Scanner; public class MM { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int num=sc.nextInt(); System.out.println(num%3==0?true:false); } }

运行结果:
5false