Problem overview
The method lastTwoDigitSum(int n) receives a non-negative integer with at least two digits and returns the sum of its last two digits. For n = 2379 the last two digits are 7 and 9, so the answer is 16.
The task does not need a loop or a string. Two integer operators, remainder (%) and integer division (/), pull the digits apart.
Approach: remainders and integer division
In base 10, dividing by 10 or 100 and looking at the remainder picks out the low digits:
n % 10is the last digit.2379 % 10 = 9.n % 100is the number formed by the last two digits.2379 % 100 = 79.- For a two-digit number
x,x / 10is its first digit.79 / 10 = 7, because dividing twointvalues in C++ throws away the fractional part.
So first reduce n to its last two digits with % 100, then split that two-digit number into a ones digit (% 10) and a tens digit (/ 10), and add them.
The same two operators extend to any number of digits. Repeating "take n % 10, then replace n with n / 10" in a loop peels off the digits one at a time, which is how you would sum all the digits of a number. Here only two digits are needed, so no loop is required.
Step by step
- Take the last two digits.
int lastTwoDigits = n % 100;gives 79 for 2379. - Take the last digit of that number:
lastTwoDigits % 10, which is 9. - Take the second-to-last digit of
n, which is the first digit oflastTwoDigits:lastTwoDigits / 10, which is 7. Both operands areint, so the division gives a whole number. - Return the sum of the two, 9 + 7 = 16.
The solution in C++
class Solution {
public:
int lastTwoDigitSum(int n) {
int lastTwoDigits = n % 100;
int lastDigit = lastTwoDigits % 10;
int secondLastDigit = lastTwoDigits / 10;
return lastDigit + secondLastDigit;
}
};
Two C++ points to keep in mind:
- Integer division truncates. If either operand is a
double, the result is adouble:79 / 10is 7, but79 / 10.0is 7.9. Keeping both sides asintis what makes this work. - The sign of
%. In C++ the result of%takes the sign of the left operand, and division truncates toward zero. For-2379,% 100gives -79 and the digit sum comes out negative. The statement promises a non-negativen, so this does not arise here.
Complexity
Time and space are both O(1): a fixed number of arithmetic operations, whatever the size of n.
Edge cases and common mistakes
- A zero in the tens place. For
n = 105,n % 100is 5, solastTwoDigits / 10is 0 and the sum is 5. That is right: the last two digits are 0 and 5. - Exactly two digits. For
n = 99,n % 100is 99 and the answer is 18. Forn = 10it is 1. - Multiples of 100. For
n = 100the last two digits are 0 and 0, and the answer is 0. - Dividing instead of taking the remainder.
n / 100removes the last two digits and keeps the rest, the opposite of what is needed. - Converting to a string. It works, but it is slower and needs extra code to turn characters back into digits. The arithmetic version is shorter.
Testing
2379gives 16.10gives 1.99gives 18.100gives 0.105gives 5.
