+ 1

# how to extract digits beginning from the first digit ?

3 Answers

+ 4

Here's a little program to treat an integer like an array. You can get the digit at its index (zero based).
#include <iostream>
#include <stdexcept>
#include <sstream>
using namespace std;
int getNumberOfDigits(int number) {
int length = 1;
while((number /= 10) != 0){
++length;
}
return length;
}
int getDigitAtIndex(int number, int index) {
int numAtIndex = 0;
int count = getNumberOfDigits(number) - index;
if(index < 0 || count <= 0) {
stringstream str;
str << "Index of " << index << " is out of range";
throw out_of_range(str.str());
}
for(int i = count; i > 0; --i) {
numAtIndex = number % 10;
number /= 10;
}
return numAtIndex;
}
int main() {
int number = 12345;
cout << getDigitAtIndex(number, 0);
return 0;
}

+ 5

The striaght-forward/naive way would be keep dividing the integer by 10 and get the last non-zero quotient.
567 Ă· 10 = 56
56 Ă· 10 = 5 âŹ
5 Ă· 10 = 0

0

yep as he âsaid for getting from back
a[ i ]=n%10;
n/10;
or to get from front
while(size){
a[ i ] = n/exp(10, --size);
n-=exp(10,size+1);}
here size is no. of digits in n