For example, 42556
. How do I determine first digit if I don't know the number of digits in the number? I could't find an algorithm that suits me anywere! (I mean to determine the 4 in 42556)
Asked
Active
Viewed 5,111 times
-3

Mureinik
- 297,002
- 52
- 306
- 350

The Emerald Cave
- 43
- 1
- 7
-
@MikeDunlavey i thought that;s how i determine the last number( the 6) – The Emerald Cave May 28 '16 at 12:28
-
@MikeDunlavey Won't that give you the last digit, the 6 in this case? – nicomp May 28 '16 at 12:28
-
1**last** in the title, **first** in the question = instant downvote. – LogicStuff May 28 '16 at 12:34
-
I know you have an answer now. But, if I didn't know that way, I would convert to string and extract first character. But I realise that is not very good compared to the answers. – Andrew Truckle May 28 '16 at 14:44
5 Answers
2
You could keep on dividing it by 10 until you've reached the last digit:
int lastDigit(int n) {
n = abs(n); // Handle negative numbers
int ret = n;
while (n > 0) {
ret = n % 10;
n /= 10;
}
return ret;
}

Mureinik
- 297,002
- 52
- 306
- 350
2
Assuming a
is the input number.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
long a = 42556;
long num;
num=floor(log10(a))+1;
//cout<<num<<" "<<"\n"; //prints the number of digits in the number
cout<<a/(int)pow(10,num-1)<<"\n"; //prints the first digit
cout<<a%10<<"\n"; //prints the last digit
return 0;
}
Live demo here.

abhishek_naik
- 1,287
- 2
- 15
- 27
-
-
1i saw u answerinfg a lot of questions latley on stack overflow – The Emerald Cave May 28 '16 at 12:34
-
The +1, -1 operations are needless unless you uncomment out the commented line – LTPCGO Feb 21 '20 at 17:02
1
Iteratively divide by 10 until the result is less than 10.
num = 42556
while num > 9
num = num / 10

nicomp
- 4,344
- 4
- 27
- 60
1
All answers assumed you have an integer number. But generally, you can first get the integer form using the function floor
from <cmath>
, i.e.
#include <cmath>
int getlastdigit(double number)
{
long long n = (long long)floor(number);
while(n > 9)
n /= 10;
return n;
}

polfosol ఠ_ఠ
- 1,840
- 26
- 41
0
Try this:
int firstdigit(int n) {
int x = n;
while(n != 0) {
x = n%10;
n = n/10;
}
return x;
}

Priyansh Goel
- 2,660
- 1
- 13
- 37
-
@DragosStamatin : There is a better way to thank on stack overflow. You can upvote/accept the answer – Priyansh Goel May 28 '16 at 13:14
-
@drescherjm : Thanks for pointing this out. That was a silly mistake I made – Priyansh Goel May 28 '16 at 14:33
-
1
-
@greybeard, could you please elaborate? For `n=0`, the value of `x` would be `0`, which in turn is returned. – abhishek_naik May 28 '16 at 16:10