extracting value from a given number

i want to extract a digit from a given number and given position in minimum time
ie:- given number is 45678
i want to extract 3rd digit(6) from the left in minimum time complexity!(using minimum loops)
thanks in advance!

 
1
2
3
4
5
6
7
8
9
10
//look ma, no loops
#include <string>
#include <iostream>

int main()
{
    std::string s = std::to_string(45678);
    char f = s[2];
    std::cout << f;
}
6


Last edited on
sorry i forgot to mention without using string!
1
2
3
4
5
6
7
8
9
10
11
//look ma, no string
#include <stringstream>
#include <iostream>

int main()
{
    std::ostringstream s;
    s << 45678;
    char f = s.str()[2];
    std::cout << f;
}
6
Another two options:
1) Using files
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>
#include <fstream>

int main()
{
    const int num = 45678;
    const int pos = 3;
    {
        std::ofstream x("temp"); //should really use boost temporary file function here
        if(!x.is_open())
            return 1;
        x << num;
        x.close();
    }
    char c;
    {
        std::ifstream x("temp");
        if(!x.is_open())
            return 1;
        for(int i = 0; i < pos; ++i)
            x >> c;
        x.close();
    }
    std::cout << c;
}
6
2) Using MATH magic:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cmath>

int main()
{
    const int num = 45678;
    const int pos = 3;
    int size = std::floor(std::log10(num));
    int rpos = size + 1 - pos;
    int digit = (num / static_cast<int>(std::pow(10, rpos))) % 10;
    std::cout << digit;
}
6
Last edited on
thanks a lot :)
This may not be fast because its recursion, but it uses 0 loops. This function works by assuming the last digit of your number is index 0. So if you want the first, or most significant digit of a 5 digit number you would call this function with the index parameter of 4.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int nthDigit(unsigned long, unsigned);

int main()
{
    unsigned long number = 0;
    unsigned index = 0;
    cout << "number: ";
    cin >> number;
    cout << "index: ";
    cin >> index;
    cout << nthDigit(number, index) << endl;
}

int nthDigit (unsigned long number, unsigned n)
{
    if(n == 0)
        return number % 10; 
    if(number < 10) 
        return -1; 
    return nthDigit(number / 10, n - 1); 
}



number: 654321
index: 3
4

number: 6543210
index: 3
3


It will also return -1 if you went out of bounds, for example wanting the 6th digit of a four digit number.

number: 5968
index: 6
-1
Last edited on
Topic archived. No new replies allowed.