0

Hello, can you explain to me why we used 10? I could not understand the solution to the question

#include <iostream> using namespace std; int main() { // sample number int num ; cin>>num; //reverse the number int r, temp; int sum = 0; for(temp = num; num != 0; num /= 10) { r = num % 10; sum = sum * 10 + r; } //compare the numbers if(temp == sum) cout << temp << " is a palindrome"; else cout << temp << " is NOT a palindrome"; return 0; }

19th May 2022, 2:37 AM
Soneta
Soneta - avatar
2 Answers
+ 1
Soneta 10 is used to get reminder and division and multiplication to get reverse number. Why divide with 10 because we want to break loop at some point. We get reminder then multiply with 10 in previous sum then add that reminder value to get new sum. This process will go until we don't break loop and get reversed number Explanation with example: 123 here we have to get reminder first then multiply with 10 So 123 % 10 = 3 and sum * 10 + 3 = 3 Now 123 / 10 = 12 Now new number is 12 So 12 % 10 = 2 and sum * 10 + 2 = 3 * 10 + 2 = 32 Remember previous sum was 3 Now new sum is 32 Now divide 12 by 10 so 12 / 10 = 1 Now new number is 1 So 1 % 10 = 1 and sum * 10 + 1 = 32 * 10 + 1 = 320 + 1 = 321 Remember previous sum was 32 now new sum is 321 which is reverse number of 123 So 123 == 321 which is false means NOT a palindrome
19th May 2022, 3:21 AM
A͢J
A͢J - avatar
+ 1
A͢J Thank you so much
19th May 2022, 12:05 PM
Soneta
Soneta - avatar