Check if a large number is divisible by 11 or not in java



A number is divisible by 11 if the difference between the sum of its alternative digits is divisible by 11.

i.e. if (sum of odd digits) – ( sum of even digits) is 0 or divisible by 11 then the given number is divisible by 11.

Program

import java.util.Scanner; public class DivisibleBy11 {    public static void main(String args[]) {       Scanner sc = new Scanner(System.in);       System.out.println("Enter a number :");       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");       }    } }

Output

Enter a number : 121 Given number is divisible by 11
Updated on: 2020-06-25T12:03:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements