2119. A Number After a Double Reversal
Description
Reversing an integer means to reverse all its digits.
- For example, reversing
2021
gives1202
. Reversing12300
gives321
as the leading zeros are not retained.
Given an integer num
, reverse num
to get reversed1
, then reverse reversed1
to get reversed2
. Return true
if reversed2
equals num
. Otherwise return false
.
Example 1:
Input: num = 526 Output: true Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num.
Example 2:
Input: num = 1800 Output: false Explanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num.
Example 3:
Input: num = 0 Output: true Explanation: Reverse num to get 0, then reverse 0 to get 0, which equals num.
Constraints:
0 <= num <= 106
Solutions
Solution 1: Mathematics
If the number is $0$, or the last digit of the number is not $0$, then the number after reversing twice will be the same as the original number.
The time complexity is $O(1)$, and the space complexity is $O(1)$.
Python3
class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return num == 0 or num % 10 != 0
Java
class Solution {
public boolean isSameAfterReversals(int num) {
return num == 0 || num % 10 != 0;
}
}
C++
class Solution {
public:
bool isSameAfterReversals(int num) {
return num == 0 || num % 10 != 0;
}
};
Go
func isSameAfterReversals(num int) bool {
return num == 0 || num%10 != 0
}
TypeScript
function isSameAfterReversals(num: number): boolean {
return num === 0 || num % 10 !== 0;
}
Rust
impl Solution {
pub fn is_same_after_reversals(num: i32) -> bool {
num == 0 || num % 10 != 0
}
}
JavaScript
/**
* @param {number} num
* @return {boolean}
*/
var isSameAfterReversals = function (num) {
return num === 0 || num % 10 !== 0;
};