Find the last digit of a given integer, handling both positive and negative numbers.
For instance:
- For 123, the last digit is 3.
- For −352, the last digit is 2.
Approach:
- Calculate the last digit using the modulus operator % 10.
- If the number is negative, use the abs() function to convert the last digit to a positive value.
#include <bits/stdc++.h>
using namespace std;
int main() {
int posNum = 123; // Positive number
int negNum = -235; // Negative number
// Last digit for positive number
int lastDigitPos = (posNum % 10);
cout << "Last digit of " << posNum << " is " << lastDigitPos << endl;
// Last digit for negative number
int lastDigitNeg = abs(negNum % 10);
cout << "Last digit of " << negNum << " is " << lastDigitNeg << endl;
return 0;
}
Output
Last digit of 123 is 3 Last digit of -235 is 5