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.
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);
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With