Wednesday, March 1, 2023
HomeSoftware EngineeringMethods to Discover the nth Reverse Quantity in Java

# Methods to Discover the nth Reverse Quantity in Java

## The problem#

Reverse Quantity is a quantity which is similar when reversed.

For instance, the primary 20 Reverse Numbers are:

``````0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101
``````

Activity

• It’s worthwhile to return the nth reverse quantity. (Assume that reverse numbers begin from 0 as proven within the instance.)

Notes

Choice 1:

``````import java.math.BigInteger;

public class Palindrome {

personal static int size = 0;

public static BigInteger findReverseNumber(lengthy n) {
if (n == 1) {
return BigInteger.ZERO;
}
size = 0;
String the rest = findLengthAndRemainder(n - 1);
whereas (the rest.size() < (size + 1) / 2) {
the rest = "0" + the rest;
}
StringBuilder consequence = new StringBuilder();
if (the rest.matches("d0*")) {
consequence.append(the rest.charAt(0));
consequence.append("9".repeat(the rest.size() - 1));
} else {
consequence.append(Integer.parseInt(the rest.substring(0, 1)) + 1);
String worth = String.valueOf(new BigInteger(the rest.substring(1)).subtract(BigInteger.ONE));
whereas (worth.size() < the rest.size() - 1) {
worth = "0" + worth;
}
consequence.append(worth);
}
String firstHalf = consequence.toString();
String secondHalf = consequence.reverse().substring(size % 2);
return new BigInteger(firstHalf + secondHalf);
}

personal static String findLengthAndRemainder(lengthy quantity) {
lengthy subtract = 9;
whereas (quantity > 0) {
size++;
quantity -= subtract;
if (quantity <= 0) {
break;
}
size++;
quantity -= subtract;
if (quantity > 0) {
subtract *= 10;
}
}
quantity += subtract;
return String.valueOf(quantity);
}

}
``````

## Take a look at instances to validate our resolution#

``````import org.junit.jupiter.api.Take a look at;

import java.math.BigInteger;

import static org.junit.jupiter.api.Assertions.assertEquals;

class PalindromeTest {

@Take a look at
void testFixed() {
assertEquals(new BigInteger("0"), Palindrome.findReverseNumber(1));
assertEquals(new BigInteger("1"), Palindrome.findReverseNumber(2));
assertEquals(new BigInteger("9"), Palindrome.findReverseNumber(10));
assertEquals(new BigInteger("909"), Palindrome.findReverseNumber(100));
assertEquals(new BigInteger("900000000000000000009"), Palindrome.findReverseNumber(100000000000L));
}

}
``````

RELATED ARTICLES