Oct 11, 2013 at 12:10pm UTC
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 Oct 11, 2013 at 12:11pm UTC
Oct 11, 2013 at 12:24pm UTC
sorry i forgot to mention without using string!
Oct 11, 2013 at 12:56pm UTC
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 Oct 11, 2013 at 12:59pm UTC
Oct 12, 2013 at 3:13am UTC
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.
Last edited on Oct 12, 2013 at 3:18am UTC