检查是否在Java中将一个大数除以3

如果一个数字的位数之和可被3整除,则该数字可被3整除。

被3整除的数字的一些示例如下。

  • 数字85203可被3整除,因为其数字的总和(8 + 5 + 2 + 0 + 3 = 18)可被3整除。

  • 数字79154不能被3整除,因为其数字的总和(7 + 9 +1 + 5 + 4 = 26)不可以被3整除。

程序

import java.util.Scanner;

public class DivisibleBy3 {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("输入数字:");
      String num = sc.nextLine();
      int digitSum = 0;
     
      for(int i = 0; i<num.length(); i++) {
         digitSum = digitSum + num.charAt(i)-'0';
      }
      if(digitSum % 3 == 0) {
         System.out.println("Given number is divisible by 3");
      } else {
         System.out.println("Given number is not divisible by 3");
      }
   }
}

输出结果

输入数字:
85203
Given number is divisible by 3