How to extract the last N digits from a number in Java

1 Answer

0 votes
public class LastNDigits {

    /**
       Extracts the last N digits from a given number.

       The approach:
         - To get the last N digits, compute: number % (10^N)
         - This avoids string manipulation and is efficient.

       Parameters:
         number : the original integer
         digits : how many digits to extract from the end

       Returns:
         The last N digits as an integer.
    */
    public static int getLastNDigits(int number, int digits) {
        // Compute 10^digits using Math.pow (returns double)
        // Cast to int because modulo requires integer operands
        int divisor = (int) Math.pow(10, digits);

        // Modulo gives the remainder, which is exactly the last N digits
        return number % divisor;
    }

    public static void main(String[] args) {

        // Example values
        int number = 987654321;
        int digits = 4;

        // Extract the last N digits
        int result = getLastNDigits(number, digits);

        // Display the result
        System.out.println("Original number: " + number);
        System.out.println("Digits requested: " + digits);
        System.out.println("Last " + digits + " digits: " + result);
    }
}


/*
run:

Original number: 987654321
Digits requested: 4
Last 4 digits: 4321

*/

 



answered Sep 18 by avibootz
...