0

display palindrome from 1 to n

plz use loops only

6th Sep 2016, 6:11 PM
Mayan Pahwa
Mayan Pahwa - avatar
1 Antwort
+ 1
Here is my shot at it: http://www.sololearn.com/app/cplusplus/playground/cTwgvFvpR1nu/ void printPalindromes(unsigned int n) { unsigned int i, num, pal; bool numDigitsEven; pal = 1; numDigitsEven = false; for (num = 1; pal < n; num++) { pal = num; if (numDigitsEven) { i = num; } else { i = num/10; } for (; i > 0; i = i/10) { pal = pal*10 + i%10; } cout << pal << endl; for (i = num; i%10==9; i=i/10) {} if (i == 0) { if (!numDigitsEven) { num = num/10; numDigitsEven = true; } else { numDigitsEven = false; } } } } An alternative version, which is probably the standard way to do it (but is slower): void printPalindromes2(unsigned int n) { unsigned int i, rev, i2; for (i = 1; i <= n; i++) { i2 = i; rev = 0; while (i2 > 0) { rev = rev*10 + i2%10; i2 = i2/10; } if (rev == i) { cout << i << endl; } } }
6th Sep 2016, 11:50 PM
Zen
Zen - avatar