The obstacle
Reverse Number is a number which is the exact same when reversed.
For instance, the very first 20 Reverse Numbers are:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101
Job
- You require to return the nth reverse number. (Presume that reverse numbers begin with 0 as displayed in the example.)
Notes
The option in Java
Choice 1:
import java.math.BigInteger;
public class Palindrome {
personal fixed int length = 0;
public fixed BigInteger findReverseNumber( long n) {
if (n == 1) {
return BigInteger.ZERO;
}
length = 0;
String rest = findLengthAndRemainder( n - 1);.
while (remainder.length() < < (length + 1)/ 2) {
rest="0" + rest;.
}
StringBuilder outcome = brand-new StringBuilder();.
if (remainder.matches(" d0 *")) {
result.append( remainder.charAt( 0 ));.
result.append(" 9". repeat( remainder.length() - 1));.
} else {
result.append( Integer.parseInt( remainder.substring( 0, 1)) + 1);.
String worth = String.valueOf( brand-new BigInteger( remainder.substring( 1 )). deduct( BigInteger.ONE));.
while (value.length() < < remainder.length() - 1) {
worth="0" + worth;.
}
result.append( worth);.
}
String firstHalf = result.toString();.
String secondHalf = result.reverse(). substring( length % 2);.
return brand-new BigInteger( firstHalf + secondHalf);.
}
personal fixed String findLengthAndRemainder( long number) {
long deduct = 9;.
while (number > > 0) {
length++;.
number -= deduct;.
if (number < 0) {
deduct *= 10;.
}
}
number += deduct;.
return String.valueOf( number);.
}
}
Test cases to confirm our option
import org.junit.jupiter.api.Test;.
import java.math.BigInteger;.
import fixed org.junit.jupiter.api.Assertions.assertEquals;.
class PalindromeTest {
@Test.
void testFixed() {
assertEquals( brand-new BigInteger(" 0"), Palindrome.findReverseNumber( 1 ));.
assertEquals( brand-new BigInteger(" 1"), Palindrome.findReverseNumber( 2 ));.
assertEquals( brand-new BigInteger(" 9"), Palindrome.findReverseNumber( 10 ));.
assertEquals( brand-new BigInteger(" 909"), Palindrome.findReverseNumber( 100 ));.
assertEquals( brand-new BigInteger(" 900000000000000000009"), Palindrome.findReverseNumber( 100000000000L));.
}
}