Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

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

2 Answers

0 votes
import kotlin.math.pow

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

    Approach:
      - To get the last N digits, compute: number % divisor
      - Where divisor = 10^digits.
*/
fun getLastNDigits(number: Int, digits: Int): Int {
    // Compute 10^digits using Double.pow, then convert to Int
    val divisor: Int = 10.0.pow(digits).toInt()

    return number % divisor
}

fun main() {
    val number: Int = 987_654_321
    val digits: Int = 4

    val result: Int = getLastNDigits(number, digits)

    println("Original number: $number")
    println("Digits requested: $digits")
    println("Last $digits digits: $result")
}


/*
run:

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

*/

 



answered 2 days ago by avibootz
0 votes
/*
    Extracts the last N digits from a given number using integer arithmetic only.
*/
fun getLastNDigits(number: Int, digits: Int): Int {
    var divisor: Int = 1

    // Build 10^digits by repeated multiplication
    repeat(digits) {
        divisor *= 10
    }

    return number % divisor
}

fun main() {
    val number: Int = 987_654_321
    val digits: Int = 4

    val result: Int = getLastNDigits(number, digits)

    println("Original number: $number")
    println("Digits requested: $digits")
    println("Last $digits digits: $result")
}


/*
run:

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

*/

 



answered 2 days ago by avibootz
...