BAEL-5385 Code for Automorphic Number. (#11928)

This commit is contained in:
vaibhav007jain
2022-03-15 21:09:20 +05:30
committed by GitHub
parent 3c5aaa6b09
commit a2dbf5d892
2 changed files with 50 additions and 0 deletions
@@ -0,0 +1,31 @@
package com.baeldung.automorphicnumber;
public class AutomorphicNumber {
public static void main(String[] args) {
System.out.println(isAutomorphicUsingLoop(76));
System.out.println(isAutomorphicUsingMath(76));
}
public static boolean isAutomorphicUsingMath(int number) {
int square = number * number;
int numberOfDigits = (int) Math.floor(Math.log10(number) + 1);
int lastDigits = (int) (square % (Math.pow(10, numberOfDigits)));
return number == lastDigits;
}
public static boolean isAutomorphicUsingLoop(int number) {
int square = number * number;
while (number > 0) {
if (number % 10 != square % 10) {
return false;
}
number /= 10;
square /= 10;
}
return true;
}
}