-3

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)

Mureinik
  • 297,002
  • 52
  • 306
  • 350

5 Answers5

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
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