Pikachu
Pikachu

Reputation: 314

Nth digit from Most significant digit side

I want to write a function int returnNthDigit(long long int number, int position) {} such that it returns the Nth position digit from the left side. e.g. returnNthDigit(45006, 1); must return 4. Similarly, returnNthDigit(45006, 2); must return 5. I am not allowed to use any looping statement. Here is one solution I came up with by using loops.

#include <iostream>
#include <math.h>

int returnNthDigit(long long int number, int position)
{
    int numberOfDigits = log10(number) + 1;
    int iteration = numberOfDigits - position;
    while (iteration != 0)
    {
        number = number / 10;
        --iteration;
    }
    return number % 10;
}

int main() {
    std:: ios_base::sync_with_stdio(false);
    std:: cout << returnNthDigit(230045, 5);
    return 0;
}

Can I do better?

Upvotes: 0

Views: 307

Answers (1)

ununseptium
ununseptium

Reputation: 61

If you're allowed to use log/pow functions, you're close. Consider the input 123:

int log_base10 = log10(number); // returns 2;
int divide_by = pow(10, log_base10 - index - 1); // returns 10 if index == 2;
int answer = (number/divide_by) % 10;  // returns 2;

Be careful with log and pow though, because you are converting from floating points to integers.

You're essentially "chopping" off the lower most digits, and then inspecting the least significant digit with the % 10 operation.

If you can use strings, it's simpler:

auto str = std::to_string(number);
int answer = str[position-1] - '0';

Upvotes: 1

Related Questions