Palindrome
PALINDROME
My_CISCO:
a=input('Enter text') a=a.lower().replace(" ",'') print(a,a[::-1]) if a==[ ]: print("No") elif a==a[::-1] : print("Yes") else: print("No")
My_leetcode:
class Solution:
def isPalindrome(self, x: int) -> bool:
return str(x)==str(x)[::-1]
LEETCODE:
class Solution(object):
def isPalindrome(self, x):
if x < 0 or (x != 0 and x % 10 == 0):
return False
half = 0
while x > half:
half = (half * 10) + (x % 10)
x = x // 10
return x == half or x == half // 10
class Solution {
public:
bool isPalindrome(int x) {
string a= to_string(x);
string b=a;
// char y = a[0];
// b[0] = b[b.length()-1];
// b[b.length()-1]=y;
// if (b==a)
// return true;
// else
// return false;
for (int i = 0;i<a.length();i++)
{
b[i] = a[a.length()-1-i];
}
cout<<b;
if (b==a)
return true;
else
return false;
}
};
C++
Brute Force
class Solution {
public:
bool isPalindrome(int x) {
string s = to_string(x);
string t = s;
reverse(t.begin(), t.end());
return s == t;
}
};Optimized
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || (x != 0 && x % 10 == 0)) {
return false;
}
int half = 0;
while (x > half) {
half = half * 10 + x % 10;
x /= 10;
}
return x == half || x == half / 10;
}
};
Comments
Post a Comment