Can someone help me with this? Apparently, my first length function loop is running infinitely but I'm not able to understand the fault (that's what I understood by trying to debug it). Can someone rectify my mistake if any? I've tried calling by address in the palindrome function and by value in the length function (I just wanted to use a self made length function too)
#include <iostream>
int length(int n) {
int i {};
while (n > 0) {
n /= 10;
++i;
}
return i;
}
void pali(int* p) {
for (int i { 1 }, n { length(*p) }; i <= n / 2; ++i)
if ((*p / static_cast<int>(pow(10, i - 1))) % 10 != (*p / static_cast<int>(pow(10, n - i))) % 10) {
std::cout << "It is not a palindrome!\n";
return;
}
std::cout << "It is a palindrome :)\n";
}
int main() {
int num {};
std::cout << "Enter the number:";
std::cin >> num;
pali(&num);
}
#include <iostream>
#include <string>
#include <iterator>
void pali(const std::string& num) {
auto b { num.begin() };
auto e { num.rbegin() };
for (; std::distance(b, e.base()) > 0; ++b, ++e)
if (*b != *e) {
std::cout << "Is not a palindrome\n";
return;
}
std::cout << "Is a palindrome\n";
}
int main() {
int num {};
std::cout << "Enter the number:";
std::cin >> num;
pali(std::to_string(num));
}
its worth your time to write an integer power function anyway, both int to int power and double to int power. Its faster than pow & solves the issues listed. A good start to a personal tool library.
(int)log10(number)+1 is its length. or, you can round up the log to next decimal (is that ceil? I rarely use those). anyway its a one-liner though you don't need it explicitly here (shown above).
this seems like a problem with a cute solution... hmm..