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?
Aucun commentaire:
Enregistrer un commentaire