BAEL-5385 Code for Automorphic Number. (#11928)
This commit is contained in:
		
							parent
							
								
									3c5aaa6b09
								
							
						
					
					
						commit
						a2dbf5d892
					
				| @ -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; | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -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)); | ||||||
|  |     } | ||||||
|  | } | ||||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user