+ 5

How do we reverse a number? How do we check if a number is a palindrome?

19th Apr 2021, 5:08 AM
Kruti
Kruti - avatar
13 Respostas
+ 3
U can do this: #include <iostream> #include <algorithm> using namespace std; int main() { int num; cin >> num; string str = to_string(num); reverse(str.begin(), str.end()); int reversed = stoi(str); cout<< boolalpha << (reversed == num); return 0; }
19th Apr 2021, 7:42 AM
Mohan
Mohan - avatar
+ 3
#include <iostream> using namespace std; int main() { int n , num, digit, rev=0; cout << " Please Enter a number " << endl; cin>>num; n=num; do{ digit=num%10; rev=(rev*10)+digit; num=num/10; } while(num!=0); cout<<" The reverse of a number is "<<rev<<endl; if(n==rev){ cout<<" The number is Palindromic"<<endl; } else cout<<" The number is not a Palindromic"<<endl; return 0; }
20th Apr 2021, 10:16 PM
Darkwa John
Darkwa John - avatar
+ 2
Use a while or a do while loop Take off the remainders from that number and check whether it is matching with the original number or not
19th Apr 2021, 5:15 AM
Atul [Inactive]
+ 2
Thanks!
19th Apr 2021, 5:22 AM
Kruti
Kruti - avatar
+ 2
There are at least two variants to reverse a number: 1. Iterate through the digits of a number: ```c++ // suppose we have the initial number as variable x of some integer type auto a = x, y = x / x - 1; // to do them the same type for (int i = a % 10; a; a /= 10, i = a % 10) y = y * 10 + i; ``` To know if the number is palindromic, use `x == y`. 2. Make it a string and reverse it: ```c++ // the same x variable is used #include <string> // if <iostream> is already included, there is no need in this line string a = to_string(x), y = ""; for (auto chr = a.crbegin(); chr != a.crend(); chr++) y.push_back(*chr); ``` To know if the number is palindromic, use `a == y`.
19th Apr 2021, 5:23 AM
#0009e7 [get]
#0009e7 [get] - avatar
+ 2
Tapabrata Banerjee better if you had provided the explanation only . Because it may or may not be helpful to the learner. Next time be careful on this matter
19th Apr 2021, 5:34 AM
Atul [Inactive]
20th Apr 2021, 10:15 PM
Darkwa John
Darkwa John - avatar
+ 1
Yes but this approach will be better. If you first give some hint and then also if the learner is unable to solve then provide the code with comments in it
19th Apr 2021, 5:37 AM
Atul [Inactive]