如果一个数字的备用位数字总和之差可被11整除,则该数字可被11整除。
例如,如果(奇数位数的总和)–(偶数位数的总和)为0或可被11整除,则给定数字可被11整除。
import java.util.Scanner; public class DivisibleBy11 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("输入数字:"); String num = sc.nextLine(); int digitSumEve = 0; int digitSumOdd = 0; for(int i = 0; i<num.length(); i++) { if(i%2 == 0) { digitSumEve = digitSumEve + num.charAt(i)-'0'; } else { digitSumOdd = digitSumOdd + num.charAt(i)-'0'; } } int res = digitSumOdd-digitSumEve; if(res % 11 == 0) { System.out.println("Given number is divisible by 11"); } else { System.out.println("Given number is not divisible by 11"); } } }
输入数字: 121 Given number is divisible by 11