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

View File

@ -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;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.automorphicnumber;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
public class AutomorphicNumberUnitTest {
@Test
void givenANumber_whenPassed_thenShouldDetermineAutomorphicOrNot() {
int number1 = 76; // automorphic
int number2 = 16; // not automorphic
assertTrue(AutomorphicNumber.isAutomorphicUsingLoop(number1));
assertFalse(AutomorphicNumber.isAutomorphicUsingLoop(number2));
assertTrue(AutomorphicNumber.isAutomorphicUsingMath(number1));
assertFalse(AutomorphicNumber.isAutomorphicUsingMath(number2));
}
}