Find an nth element in an integer number

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 using namespace std;
#include <iostream>
int main()
{
	int x, T , ct = 0  ; 
	cout << "Number: ";
	cin >> x;
	T = x;
	while( x!= 0)
	{
		ct++;
		x /= 10;
	}
	int* arr = new int[ct];
	ct--;
	while (T != 0)
	{
		arr[ct--] = T % 10;
		T /= 10;
	}
	cout << "Element? ";
	int e; cin >> e;
	cout << endl << arr[--e];
	return 0;
}
Last edited on
If you ask for the element before the calculation, you only need find the specific one you're interested in.

Rather than having to store all of them, only to then find out you only need one of them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
using namespace 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
@jonnin

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>
using namespace 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;
}
Last edited on
partially. Here, no loops:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
#include<cmath>
using namespace 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;
}




Last edited on
Topic archived. No new replies allowed.