Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last digit of a number

Tags:

c#

How to get the last digit of a number? e.g. if 1232123, 3 will be the result

Some efficient logic I want so that it is easy for results having big numbers.
After the final number I get, I need to some processing in it.

like image 924
mns Avatar asked Mar 31 '13 16:03

mns


People also ask

How do you print the last digit?

digit = num % 10; We find out the last digit of the number by dividing it by 10, this gives us the remainder which is the last digit of the number. printf("Last Digit of %d is: %d", num, digit); // Displaying output printf("Last Digit of %d is: %d", num, digit);

How do you find the digits of a number?

The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.

How do you find the last digit of a sequence?

Except when the terms are negative, last digits can be obtained by using modular arithmetic and working “modulo 10”, “ 54 mod 10” is 4, “12 mod 10” is 2, etc. So for the most part, instead of saying "last digit" we can just say “mod 10” to get the last digits.


1 Answers

Just take mod 10:

Int32 lastNumber = num % 10; 

One could use Math.Abs if one's going to deal with negative numbers. Like so:

Int32 lastNumber = Math.Abs(num) % 10; 
like image 188
acrilige Avatar answered Sep 22 '22 23:09

acrilige