a lot easier and you are using a data structure; #O(n) tmp_str = str(x) if tmp_str[::-1] == str(x): return True else: return False was my solution O(n) time too
Great solution, thank you! The solution implemented in c#: public bool IsPalindrome(int x) { if (x < 0) { return false; } long divider = 1; while (divider * 10 0) { int l = (int) (x / divider); int r = (int) (x % 10); if (l != r) { return false; } // Cut the left digit x = (int) (x % divider); // Cut the right digit x /= 10; divider /= 100; } return true; } divider is in long type due to case the given x is one digit less the max int value. Another solution, write the reserved number and compare it to the given x. implemented in c#: public bool IsPalindrome(int x) { if (x < 0) { return false; }
int reservedNumber = 0; int originalX = x; while (x > 0) { int lastDigit = x % 10; reservedNumber = reservedNumber * 10 + lastDigit; x /= 10; } return reservedNumber == originalX; }
I feel like this is a simpler approach: public class Solution { public bool IsPalindrome(int x) { if(x < 0) return false; if (x != 0 && x % 10 == 0) return false; int original = x; int reversed = 0; while (x != 0) { reversed = reversed * 10 + x % 10; x /= 10; } return original == reversed; } }
3 ปีที่แล้ว +8
This was my C# solution (which is similar to yours) that I submitted a while ago; if(x == 0) return true; if(x < 0 || x % 10 == 0) return false;
var reverse = 0;
while(x > reverse) { var lastDigit = x % 10; x /= 10; reverse = reverse * 10 + lastDigit; }
A simple solution using JS. The idea is to reverse the number and then compare it to the original one. var isPalindrome = function(x) { if (x < 0) return false; let num = x; let result = 0; while (num > 0) { result = result * 10 + (num % 10); num = Math.floor(num / 10); } return result === x; };
I think this video may need a remake because it will not work when the input is 1410110141 on Java. I tried this and it worked: if (x < 0 || (x % 10 == 0 && x != 0)) { return false; } else { int original = x, reversed = 0; while (original > reversed) { reversed = (reversed * 10) + (original % 10); original /= 10; } return original == reversed || original == reversed / 10; }
What if you try to recreate the number by chopping its rightmost value and add it back: for example 121 i break it by doing % 10 to get the 1 from the right side, then do *10 and adding 20 and so on and in the end you check if x is equal to your new formed value (y let's say) if true that's what you return as well.
Will this solution work for this testcase? 1000021 Because, once we remove the first and the last letter and proceed to the next step, we have 000021 which is evaluated as 21
@@odinson4184 Because that is how it is supposed to work. You loop over and over again. 120021 for example goes to 2002 - 00. You always strip the outer two numbers and check with if left != right if they matchup. At the point where they don't you return false. In your case with 100021 you strip the left and right number: 0002. Then in the next loop you get the left with 0002//1000 = 0 and the right with 0002%10 = 2. Which in turn returns False with left != right. EDIT: I think I've noticed the error in your thinking. You mentioned that 00021 returns 21 correct? That is not how Modulos works. It first divides 20 by 10 which is 2 and dismisses it. Then it takes the 1 and divides it again by 10, which, of course, doesn't work and returns 1. The Modulo Operator always returns the digit it can't divide.
@@odinson4184 Well it works for me, I don't know what your problem is. To strip the left 1 you divide by "div". For the right 1 you use x%10. I honestly don't know why it doesn't work for you.
Thank you for the solution! But I’m struggling to understand why we should chop off the left and right digits, couldn’t we just compare then and if they are equal return True? Please if someone could explain, I would be much grateful!
the last condition returns False clarify that if the middle numbers are equal then True. we need to remove right and left numbers so that we can compare the middle numbers.
Do you know how to fix this code to work with 0’s on both ends, say you end up with 0110, I think the computer will ignore the first 0 so it’ll try to match 1 and 0 which will return false, idk if this happens on python but i’m doing it in java
class Solution: def isPalindrome(self, x: int) -> bool: list1=[] import math y = [a for a in str(x)] for i in range(0,math.floor(len(y)/2)+1): if y[i]!=y[-i-1]: list1.append(1) else: list1.append(0) if 1 in list1: return False return True
In python for example 21//10 (note the double division sign) it returns integer division which will be 2, and to understand it think of it as first we do simple division which result will be 2.1 but then discard decimal value, so for example 3//4 will return 0 since we discarded decimal value
can anyone tell me why you gotta use oops in this when it simply can be done using if else statement correct me if i am wrong heres my code btw x=121 y=str(x)[-1::-1] z=int(y) print(z) if x == z: print("Palindrome") else: print("not a palindrome") it didnt ran on leetcode showed some sort of runtime error
@decimusmeridious4444 Because the follow up question in the problem said CAN you solve it WITHOUT convert the int to string? That's why it's not allowed that solution...(It will accept it but that not how they want you to solve it) the problem is about int manipulation....
It is interesting how the solution is here. Does it really work in python when the number is something like 10000001? My solution was something like this. It is enough fast but I wanted to have memory optimized. :( var isPalindrome = function(x) {
if (x < 0) return false if (x < 10) return true var array = [] while (x != 0) { array.push(x % 10) x = parseInt(x / 10) }
for (var i = 0; i< parseInt(array.length / 2); i++) { var start = array[i] var end = array[array.length - (i + 1)] if (start != end) return false }
@Chris Sun because the line right above it is modifying x by a factor of 100 (by chopping off two digits). If you reduce x from 1221 to 22, you want your div to go from 1000 (used for 1221), to 10 (to be used for 22).
damn, I just converted the number to a string, used [::-1] to turn it around, converted it to a number again with int, and compared it with the original x, I think something is wrong with me
The answer should be O(N), the worst case is when the program checks a positive palindrome number, every time the number is chopped off by 2 digits, then the whole process will contain N/2 iteration steps.
@@davisonyeoguzoro9232 Late response but esentially every step of the loop you reduce the size of the number by 2, so if you have a 20 numbers integer it will take 10 steps to reduce it completely. This scales linearily and thus is O(n/2) which is O(n)
return str(x) == str(x)[::-1] Runtime: 115 ms, faster than 21.82% of Python3 online submissions for Palindrome Number. Memory Usage: 13.9 MB, less than 90.68% of Python3 online submissions for Palindrome Number.
Nice! But it doesn't cover the follow up question "Could you solve it without converting the integer to a string?". This video shows the follow up question's solution.
I did this in Java. Runtime and memory same to be the same as above solution. public boolean isPalindrome(int x) { if(x == 0) return true; if(x < 0 || x % 10 == 0) return false; List arr = new ArrayList(); while(x > 0){ int temp = x%10; x=x/10; arr.add(temp); } int start = 0, end = arr.size() - 1; while(start
Is this solution good? number = int(input()) list = [] new_list = list.append(number) print(list) string = str(number) new_string=string[::-1] new_string1 = int(new_string) list2 = [new_string1] if list[0]==list2[0]: print("It is pallindrome") else: print("It is not pallindrome")
thanks for making me more confused
it's pretty simple sir, please do put some efforts
Are you ASIAN?
Nice Solution!
We can write the divider value in this way as well 8:37:
if x==0: return True
div = 10**int(math.log10(x))
bro ain't nobody trynna use the log function
You have to take the floor of the log
watched this and did it using strings, gave myself a pat on the back.
a lot easier and you are using a data structure;
#O(n)
tmp_str = str(x)
if tmp_str[::-1] == str(x):
return True
else:
return False
was my solution O(n) time too
@@esaur5310sir I didn't really understand could you explaim
Great solution, thank you!
The solution implemented in c#:
public bool IsPalindrome(int x) {
if (x < 0)
{
return false;
}
long divider = 1;
while (divider * 10 0)
{
int l = (int) (x / divider);
int r = (int) (x % 10);
if (l != r)
{
return false;
}
// Cut the left digit
x = (int) (x % divider);
// Cut the right digit
x /= 10;
divider /= 100;
}
return true;
}
divider is in long type due to case the given x is one digit less the max int value.
Another solution, write the reserved number and compare it to the given x.
implemented in c#:
public bool IsPalindrome(int x) {
if (x < 0)
{
return false;
}
int reservedNumber = 0;
int originalX = x;
while (x > 0)
{
int lastDigit = x % 10;
reservedNumber = reservedNumber * 10 + lastDigit;
x /= 10;
}
return reservedNumber == originalX;
}
I feel like this is a simpler approach:
public class Solution {
public bool IsPalindrome(int x) {
if(x < 0) return false;
if (x != 0 && x % 10 == 0) return false;
int original = x;
int reversed = 0;
while (x != 0) {
reversed = reversed * 10 + x % 10;
x /= 10;
}
return original == reversed;
}
}
This was my C# solution (which is similar to yours) that I submitted a while ago;
if(x == 0)
return true;
if(x < 0 || x % 10 == 0)
return false;
var reverse = 0;
while(x > reverse)
{
var lastDigit = x % 10;
x /= 10;
reverse = reverse * 10 + lastDigit;
}
return x == reverse || x == reverse / 10;
A simple solution using JS. The idea is to reverse the number and then compare it to the original one.
var isPalindrome = function(x) {
if (x < 0) return false;
let num = x;
let result = 0;
while (num > 0) {
result = result * 10 + (num % 10);
num = Math.floor(num / 10);
}
return result === x;
};
Simple, efficient and straight to the point. Thanks for this answer.
Easiest Way Ever :
def isPalindrome(self, x):
num = x
reverse = 0
while(x>0):
lastdigit = x%10
reverse = reverse*10+lastdigit
x = x//10
return True if reverse == num else False
Yes it's right, I think there's a type in your solution
This line should be x = x//10 instead of x = x/10
this is evergreen solution
I think this video may need a remake because it will not work when the input is 1410110141 on Java. I tried this and it worked:
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
} else {
int original = x, reversed = 0;
while (original > reversed) {
reversed = (reversed * 10) + (original % 10);
original /= 10;
}
return original == reversed || original == reversed / 10;
}
i used long long type for div and it worked
@@zawarudo6389 There is only long in Java I think. Your method works but it still runs a bit slower. Thanks for the reply though.
@@iforcollege i implemented in c++ and it was not slow even when using long long it beats 98% of cpp submissions
s = str(x)
return s == s[::-1]
This code is more effective and very simple to understand. Hope it was useful
but the follow up says we can't convert it to string
It worked for me. I don't think such condition is given in the question
What if you try to recreate the number by chopping its rightmost value and add it back:
for example 121 i break it by doing % 10 to get the 1 from the right side, then do *10 and adding 20 and so on and in the end you check if x is equal to your new formed value (y let's say) if true that's what you return as well.
Do you think this might be slower than the 2 pointer option you mention here ?
Will this solution work for this testcase?
1000021
Because, once we remove the first and the last letter and proceed to the next step,
we have
000021 which is evaluated as 21
Doesnt work for this case!
@@somanshv4992 works just fine
you need to alter the code to not change the input and just get the digits using two pointers.
This solution will fail if the number contains "0" in the middle of a number right? Like 1000021
It should not fail, I just tested it. I had this problem because my condition in the while loop was different.
@@patrickoweijane559 How? Removing the first integer from 100021 with modulos for example produces 21 instead of 00021. It doesn't work.
@@odinson4184 Because that is how it is supposed to work. You loop over and over again. 120021 for example goes to 2002 - 00. You always strip the outer two numbers and check with if left != right if they matchup. At the point where they don't you return false.
In your case with 100021 you strip the left and right number: 0002. Then in the next loop you get the left with 0002//1000 = 0 and the right with 0002%10 = 2. Which in turn returns False with left != right.
EDIT: I think I've noticed the error in your thinking. You mentioned that 00021 returns 21 correct? That is not how Modulos works. It first divides 20 by 10 which is 2 and dismisses it. Then it takes the 1 and divides it again by 10, which, of course, doesn't work and returns 1. The Modulo Operator always returns the digit it can't divide.
@@ventior6806 NO- stripping 1 from 100021 returns 21. This method just doesn't work. I copied it word for word, you have to use other method to solve.
@@odinson4184 Well it works for me, I don't know what your problem is. To strip the left 1 you divide by "div". For the right 1 you use x%10. I honestly don't know why it doesn't work for you.
Thank you for the solution! But I’m struggling to understand why we should chop off the left and right digits, couldn’t we just compare then and if they are equal return True? Please if someone could explain, I would be much grateful!
the last condition returns False clarify that if the middle numbers are equal then True. we need to remove right and left numbers so that we can compare the middle numbers.
Do you know how to fix this code to work with 0’s on both ends, say you end up with 0110, I think the computer will ignore the first 0 so it’ll try to match 1 and 0 which will return false, idk if this happens on python but i’m doing it in java
you could use decimal log for finding the divider
why don't we just reverse the number and compare?
Damm. I created a linked list and rebuilt the number in reverse and then compared it. And that too in C. 😭😭
A rather contrived problem. Not a fan. Great explanation though!
class Solution:
def isPalindrome(self, x: int) -> bool:
list1=[]
import math
y = [a for a in str(x)]
for i in range(0,math.floor(len(y)/2)+1):
if y[i]!=y[-i-1]:
list1.append(1)
else:
list1.append(0)
if 1 in list1:
return False
return True
can you explain this
why do you assume 21/10 rounds down to 2?
In python for example 21//10 (note the double division sign) it returns integer division which will be 2, and to understand it think of it as first we do simple division which result will be 2.1 but then discard decimal value, so for example 3//4 will return 0 since we discarded decimal value
Correct me if I am wrong but this solution is outdated. It fails for the test case 1000021.
class Solution:
def isPalindrome(self, x: int) -> bool:
return str(x) == str(x)[::-1]
Great explanation sir ... respect!
this one needs update, doesn't work on x0000xx
wait there are pointers in python?
Sure it's a smart solution but who tf is coming up with this in an interview (unless you've memorised it)
congrats for 350K😍
can anyone tell me why you gotta use oops in this when it simply can be done using if else statement correct me if i am wrong heres my code btw
x=121
y=str(x)[-1::-1]
z=int(y)
print(z)
if x == z:
print("Palindrome")
else:
print("not a palindrome")
it didnt ran on leetcode showed some sort of runtime error
make a simple problem very complex ...solve it..and boom people will call you INTELLECTUAL
@decimusmeridious4444
Because the follow up question in the problem said
CAN you solve it WITHOUT convert the int to string?
That's why it's not allowed that solution...(It will accept it but that not how they want you to solve it) the problem is about int manipulation....
heres mine
class Solution:
def isPalindrome(self, x: int) -> bool:
z = str(x)[::-1]
if z == str(x):
return True
else :
return False
thanks you for your solution brother !!
It is interesting how the solution is here. Does it really work in python when the number is something like 10000001?
My solution was something like this. It is enough fast but I wanted to have memory optimized. :(
var isPalindrome = function(x) {
if (x < 0) return false
if (x < 10) return true
var array = []
while (x != 0) {
array.push(x % 10)
x = parseInt(x / 10)
}
for (var i = 0; i< parseInt(array.length / 2); i++) {
var start = array[i]
var end = array[array.length - (i + 1)]
if (start != end) return false
}
return true
};
X < 10 return false will fail. One of the tests is on 0, which it expects to return true
Your solution works just fine. The 10000021 case failed, but your code handles it. But with a lot of time and space overhead.
at 11:56 Why do we do div = div / 100 and not div = div/10 ?
@Chris Sun because the line right above it is modifying x by a factor of 100 (by chopping off two digits). If you reduce x from 1221 to 22, you want your div to go from 1000 (used for 1221), to 10 (to be used for 22).
This does not work for a number like 100021
It works fine for me. The if statement return false when it does (0002//1000 != 0002%10).
class Solution(object):
def isPalindrome(self, x):
b=str(x)
c=b[::-1]
if c==b:
return True
else:
return False
time complex is very slow because converting to a string and slicing a string
Thank you!
damn, I just converted the number to a string, used [::-1] to turn it around, converted it to a number again with int, and compared it with the original x, I think something is wrong with me
there is nothing wrong with you. It's a natural solution. But every problem in leetcode is tougher than it seems
I thought the same way
Nice explanation! What would be the time complexity of the solution? O(logN) ??
The answer should be O(N), the worst case is when the program checks a positive palindrome number, every time the number is chopped off by 2 digits, then the whole process will contain N/2 iteration steps.
@@rishenglian9959 Please more explanation no this
@@davisonyeoguzoro9232 Late response but esentially every step of the loop you reduce the size of the number by 2, so if you have a 20 numbers integer it will take 10 steps to reduce it completely. This scales linearily and thus is O(n/2) which is O(n)
O(log10N) , right?
def isPalindrome(self, x: int) -> bool:
x = str(x)
if x[::-1] == x:
return True
else:
return False
we can simply change it to string?
Anyone knows why do we need to divide div by 100? The condition div = div // 100.
be were removing both the first + last digits, we change the divider by 100
impresive
How about making inverted number (java) public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int inverted = 0;
for (int target = x; target != 0; target /= 10) {
inverted = inverted * 10 + target % 10;
}
return inverted == x;
}
this version passes all the test cases on leetcode contrary to the solution proposed in the video
return str(x) == str(x) [::-1]
can you give the same solution in java pls
The "Problem Link" is wrong in your description. Please correct it.
sorry about that, fixed!
return str(x) == str(x)[::-1]
Runtime: 115 ms, faster than 21.82% of Python3 online submissions for Palindrome Number.
Memory Usage: 13.9 MB, less than 90.68% of Python3 online submissions for Palindrome Number.
Nice! But it doesn't cover the follow up question "Could you solve it without converting the integer to a string?". This video shows the follow up question's solution.
I did this in Java. Runtime and memory same to be the same as above solution.
public boolean isPalindrome(int x) {
if(x == 0)
return true;
if(x < 0 || x % 10 == 0)
return false;
List arr = new ArrayList();
while(x > 0){
int temp = x%10;
x=x/10;
arr.add(temp);
}
int start = 0, end = arr.size() - 1;
while(start
Ngl, but this is quite easy to understand. The code is short & precise, plus it works well. Thanks for sharing out the code
What if we just compare string with reversed string. Isn't that an easy solution?
def isPalindrome(self, x: int) -> bool:
if(x
thanks man that was way more easier
there is a follow up question: can you solve the problem without converting it into string?
wonderful video!
Is this solution good?
number = int(input())
list = []
new_list = list.append(number)
print(list)
string = str(number)
new_string=string[::-1]
new_string1 = int(new_string)
list2 = [new_string1]
if list[0]==list2[0]:
print("It is pallindrome")
else:
print("It is not pallindrome")
Nope, you are converting the number to a string. Not sure why are you using a list.
Check this out, much easier to visualize
class Solution:
def isPalindrome(self, x: int) -> bool:
if x
That answer is too easy, the interview question is going to want you to solve it without converting to a string
please solve top view and bottom view of binary tree
First again ❤️
K ♥️
𝕟𝕚𝕔𝕖
Does anyone came up with the c++ soln with this approach
bool isPalindrome(int x) {
if(x=10*div)
div*=10;
while(x)
{
int right=x%10;
int left=x/div;
if(left!=right)
return false;
x=(x%div)/10;
div=div/100;
}
return true;
}
What a stupid problem
lol
this is wrong
Why?
Will this work?
x_str = str(x)
return x_str == x_str[::-1]
the point is not to covert from integer to string
Thank you!
class Solution:
def isPalindrome(self, x: int) -> bool:
return (str(x)==str(x)[::-1])