From a2dbf5d892b865b3c0d1d1ea0cbe1e3477c28a44 Mon Sep 17 00:00:00 2001 From: vaibhav007jain <72961247+vaibhav007jain@users.noreply.github.com> Date: Tue, 15 Mar 2022 21:09:20 +0530 Subject: [PATCH] BAEL-5385 Code for Automorphic Number. (#11928) --- .../automorphicnumber/AutomorphicNumber.java | 31 +++++++++++++++++++ .../AutomorphicNumberUnitTest.java | 19 ++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 java-numbers-4/src/main/java/com/baeldung/automorphicnumber/AutomorphicNumber.java create mode 100644 java-numbers-4/src/test/java/com/baeldung/automorphicnumber/AutomorphicNumberUnitTest.java diff --git a/java-numbers-4/src/main/java/com/baeldung/automorphicnumber/AutomorphicNumber.java b/java-numbers-4/src/main/java/com/baeldung/automorphicnumber/AutomorphicNumber.java new file mode 100644 index 0000000000..926b13deda --- /dev/null +++ b/java-numbers-4/src/main/java/com/baeldung/automorphicnumber/AutomorphicNumber.java @@ -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; + } +} \ No newline at end of file diff --git a/java-numbers-4/src/test/java/com/baeldung/automorphicnumber/AutomorphicNumberUnitTest.java b/java-numbers-4/src/test/java/com/baeldung/automorphicnumber/AutomorphicNumberUnitTest.java new file mode 100644 index 0000000000..8e31de9f47 --- /dev/null +++ b/java-numbers-4/src/test/java/com/baeldung/automorphicnumber/AutomorphicNumberUnitTest.java @@ -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)); + } +}