Java Program to Check if all digits of a number divide it
Given a number n, find whether all digits of n divide it or not.
Examples:
Input : 128
Output : Yes
128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
Input : 130
Output : No
We want to test whether each digit is non-zero and divides the number. For example, with 128, we want to test d != 0 && 128 % d == 0 for d = 1, 2, 8. To do that, we need to iterate over each digit of the number.
Java
import java.io.*;
class GFG {
static boolean checkDivisibility( int n, int digit)
{
return (digit != 0 && n % digit == 0 );
}
static boolean allDigitsDivide( int n)
{
int temp = n;
while (temp > 0 ) {
int digit = n % 10 ;
if ((checkDivisibility(n, digit)) == false )
return false ;
temp /= 10 ;
}
return true ;
}
public static void main(String args[])
{
int n = 128 ;
if (allDigitsDivide(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Time Complexity: O(log10n), where n represents the given integer.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Please refer complete article on Check if all digits of a number divide it for more details!
Last Updated :
12 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...