palindrome integer code example
Example 1: palindrome
function isPalindrome(sometext) {
var replace = /[.,'!?\- \"]/g; //regex for what chars to ignore when determining if palindrome
var text = sometext.replace(replace, '').toUpperCase(); //remove toUpperCase() for case-sensitive
for (var i = 0; i < Math.floor(text.length/2) - 1; i++) {
if(text.charAt(i) == text.charAt(text.length - 1 - i)) {
continue;
} else {
return false;
}
}
return true;
}
//EDIT: found this on https://medium.com/@jeanpan/javascript-splice-slice-split-745b1c1c05d2
//, it is much more elegant:
function isPalindrome(str) {
return str === str.split('').reverse().join('');
}
//you can still add the regex and toUpperCase() if you don't want case sensitive
Example 2: palindrome
#include
#include
#include
bool IsPalindrome_true_false(const std::string& );
int main ()
{
std::cout<<"Please enter a string:\t";
std::string str;
getline(std::cin, str);
// convert the string from uppercase to lowercase
int i = 0;
while(str[i])
{
if(str[i] == std::toupper(str[i]) && std::isalpha(str[i]) == 1024)
str[i]+= 32;
++i;
}
// looping while string is empty
while(str.empty())
{
std::cout<<"\nPlease enter a string your string is empty:\t";
if(!str.empty())
std::string str;
getline(std::cin, str);
}
std::cout<<"\n"<
Example 3: palindrome
#include
int main() {
int n, reversedN = 0, remainder, originalN;
printf("Enter an integer: ");
scanf("%d", &n);
originalN = n;
// reversed integer is stored in reversedN
while (n != 0) {
remainder = n % 10;
reversedN = reversedN * 10 + remainder;
n /= 10;
}
// palindrome if orignalN and reversedN are equal
if (originalN == reversedN)
printf("%d is a palindrome.", originalN);
else
printf("%d is not a palindrome.", originalN);
return 0;
}