给定一个数字n,找出n的所有数字是否都除以它。
null
例如:
Input : 128 Output : Yes 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Input : 130 Output : No
我们想测试每个数字是否为非零,并对数字进行除法。例如,对于128,我们想要测试d!=0&&128%d==0表示d=1、2、8。要做到这一点,我们需要迭代每个数字。
// CPP program to check the number // is divisible by all digits are not. #include <bits/stdc++.h> using namespace std; // Function to check the divisibility // of the number by its digit. bool checkDivisibility( int n, int digit) { // If the digit divides the number // then return true else return false. return (digit != 0 && n % digit == 0); } // Function to check if all digits // of n divide it or not bool allDigitsDivide( int n) { int temp = n; while (temp > 0) { // Taking the digit of the // number into digit var. int digit = n % 10; if (!(checkDivisibility(n, digit))) return false ; temp /= 10; } return true ; } // Driver function int main() { int n = 128; if (allDigitsDivide(n)) cout << "Yes" ; else cout << "No" ; return 0; } |
输出:
Yes
请参阅完整的文章 检查一个数字的所有数字是否都除以它 更多细节!
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END