Hello I have a long long
number which varies from 13,15, and 16 digits in length. I want to get the first two digits(from the left) of these numbers.
For example:
Enter Number = 1234567890123;
First 2 digits = 12
Enter Number = 453456789012345;
First 2 digits = 45
Enter Number = 3534567890123456;
First 2 digits = 35
Repeatedly divide by 10 until 0 is reached, remembering the antepenultimate value of the number, which you will eventually return as the result.
In other words,
#include <stdio.h>
int main(void) {
long long n = 3534567890123456;
long long n1 = n, n2 = n; // n2 will hold the first two digits.
while (n){
n2 = n1;
n1 = n;
n /= 10;
}
printf("%lld", n2);
}
I initialise n1
and n2
to n
so the correct result is returned if the magnitude of n
is less than 100.
Note that this algorithm carelessly considers an unnecessary step (you don't need to run n
right down to 0
) but doing so saves having to worry about negative n
cases, and n1
also yields the first digit, which could be useful.