How to get the last digit of a big int in C++

1 Answer

0 votes
#include <iostream>
#include <string>

char getLastDigit(const std::string& bigInt) {
    // Validate input: Ensure the string contains only digits (and optional leading '-')
    for (size_t i = (bigInt[0] == '-' ? 1 : 0); i < bigInt.length(); i++) {
        if (!isdigit(bigInt[i])) {
            throw std::invalid_argument("Input is not a valid integer.");
        }
    }

    // Return the last character of the string (last digit)
    return bigInt.back();
}

int main() {
    std::string bigInt = "123456789123456789123456789123";

    try {
        // Get the last digit
        char lastDigit = getLastDigit(bigInt);

        // Output the last digit
        std::cout << "The last digit of the big integer is: " << lastDigit << std::endl;
    } catch (const std::invalid_argument& e) {
        // Handle invalid input
        std::cerr << "Error: " << e.what() << std::endl;
    }
}



/*
run:

The last digit of the big integer is: 3

*/

 



answered Aug 27, 2025 by avibootz

Related questions

1 answer 81 views
1 answer 86 views
1 answer 72 views
1 answer 71 views
1 answer 83 views
1 answer 71 views
2 answers 84 views
...