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

1 Answer

0 votes
package main

import (
    "fmt"
)

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

   Approach:
     - To get the last N digits, compute: number % (10^digits)
     - This avoids string manipulation and uses efficient arithmetic.

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

   Returns:
     The last N digits as an integer.
*/
func getLastNDigits(number int, digits int) int {
    // Build 10^digits using integer multiplication
    // Go does not have a built-in integer power function,
    // so we compute it manually.
    divisor := 1
    for i := 0; i < digits; i++ {
        divisor *= 10
    }

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

func main() {
    // Example values
    number := 987654321
    digits := 4

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

    // Display the result
    fmt.Println("Original number:", number)
    fmt.Println("Digits requested:", digits)
    fmt.Println("Last", digits, "digits:", result)
}


/*
run:

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

*/

 



answered Sep 18 by avibootz
...