Hello,
I want to find an nth element in an integer number. (from the left)
For example,
the number is = 963258741 and the fourth element is 2 or the sixth element is 8.
I wrote this program with array and it works correctly. but can we write it without array/string? I'm curious.
#include<iostream>
usingnamespace std;
int foo ( int n, int pos ) {
int c = 0;
int x = n;
while ( x ) {
c++;
x /= 10;
}
while ( c > pos ) {
c--;
n /= 10;
}
return n % 10;
}
int main()
{
int n = 963258741;
cout << "4th=" << foo(n,4) << endl;
cout << "6th=" << foo(n,6) << endl;
return 0;
}
you can use powers of 10 instead of repeated division by 10 to directly get it with that idea, since you have the position you want, you can convert that position to the right power and return n/pow10 % 10
Your mean is the below code? but first, we should calculate the number of digits. because we need fourth from the left.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream>
usingnamespace std;
int main()
{
int n = 963258741;
int c = 0;
int x = n;
while (x) {
c++;
x /= 10;
}
int a = int(n / pow(10, c-6)) % 10; //fourth element
cout << a;
return 0;
}
#include<iostream>
#include<cmath>
usingnamespace std;
int main()
{
int n = 963258741;
int c = int(log10(n)+1);
int a = int(n / pow(10, c-4)) % 10;
//fourth element from LEFT is 2
cout << a;
return 0;
}