'2119. A Number After a Double Reversal (Leetcode)
I have trying out this problem on leetcode https://leetcode.com/problems/a-number-after-a-double-reversal/
Reversing an integer means to reverse all its digits.
For example, reversing 2021 gives 1202. Reversing 12300 gives 321 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.
My logic for the above question was that if we check the last bit and if it's 0 then automatically its a false. Because reversing it would never give the same answer as 0 are not retained.
The Code:
class Solution {
public boolean isSameAfterReversals(int num) {
if(num==0) return true;
if((num|0)==0){
return false;
}
return true;
}
}
My 92 test cases are passing. But some are failing for example:
Input-1800
Output-true
Expected-false
Can someone tell me what is wrong in my logic??
Solution 1:[1]
(1800|0) evaluates to 1800 so it ends up returning false. I assume you are trying to check if the least significant digit (ones digit) is zero. You can use (num%10==0) instead
Solution 2:[2]
The problem with your code is that (num|0) is always equals to num. And, and this point, it cannot be equal to 0 because of the previous test.
How about this?
class Solution {
public boolean isSameAfterReversals(int num) {
return num == 0 || num%10 != 0;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jessica Yauney |
| Solution 2 | Maurice Perry |
