878746. Last Digit of a number
Basic
Last Digit of a Number
Summary
Given a number, find the last digit. This problem seems straightforward, but there's a catch: you have to find the last digit without actually calculating the entire value.
Detailed Explanation
The key concept here is that we can solve this problem using bitwise operations and modular arithmetic. The idea is to use bitwise operations to remove all digits except for the last one.
Here's the step-by-step breakdown:
- Convert the number to an integer.
- Use the modulo operator (
%) to find the remainder of the number when divided by 10. This will give us the last digit. - Repeat steps 1-2 until the result is a single-digit number (i.e., the last digit).
Time complexity: O(log n), where n is the input number, since we're effectively removing one digit at a time. Space complexity: O(1), since we only need a constant amount of space to store the result.
Optimized Solutions
Java
public int findLastDigit(int n) {
while (n >= 10) {
n = n % 10;
}
return n;
}