Last active
September 17, 2023 10:04
-
-
Save ikhlaqmalik13/ffed6ab918a6f54f3076cdff9f5716e9 to your computer and use it in GitHub Desktop.
Count of Arm operator numbers between range without using moduls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CountArmStrongNumbers { | |
public static int countArmStrongNumbers(int start, int range){ | |
int count = 0; | |
for(int i=start; i<range; i++){ | |
if(isArmsStrongNumberMyWAy(extractIndividualDigits(i), i)){ | |
count++; | |
} | |
} | |
return count; | |
} | |
public static boolean isArmsStrongNumberMyWAy(int[] extractedNumbers, int number){ | |
int sum = 0; | |
for(int i=0; i<extractedNumbers.length; i++){ | |
sum += Math.pow(extractedNumbers[i], extractedNumbers.length); | |
} | |
return (number == sum); | |
} | |
public static int[] extractIndividualDigits(int num) { | |
int[] individualNumbers = new int[String.valueOf(num).length()]; | |
// Enter a loop that continues as long as 'num' is greater than 0 | |
while (num > 0) { | |
// Initialize a variable 'divider' to 1 (to extract the rightmost digit) | |
int divider = 1; | |
// Enter a nested loop that continues as long as 'num' is greater than or equal to 'divider' multiplied by 10 | |
while (num >= divider * 10) { | |
divider *= 10; | |
} | |
// Calculate 'digit' as 'num' divided by 'divider' | |
int digit = num / divider; | |
// Subtract 'digit' multiplied by 'divider' from 'num' to remove the extracted digit | |
num -= digit * divider; | |
//place the elements at different locations of array , ones at 0 position , tensPosition number at 1 position and so on | |
int positionToInsert = String.valueOf(divider).length()-1; | |
individualNumbers[positionToInsert] = digit; | |
} | |
// Return the extracted digits as an array | |
return individualNumbers; | |
} | |
public static boolean isArmStrongNumberByStr(String number){ | |
int length = number.length(); | |
int sum = 0; | |
for(int i=0; i<length; i++){ | |
sum += Math.pow(Integer.parseInt(String.valueOf(number.charAt(i))), length); | |
} | |
return Integer.toString(sum).equals(number); | |
} | |
public static void main(String[] args) { | |
System.out.println(countArmStrongNumbers(1, 999)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment