Finding out whether a number is a palindrome or not in C# -
i new c# , doing program exercise. have managed program print reversed number of input given user, when move onto checking whether palindrome or not, not calculate answer correctly. prints 'not palindrome'.
after error checking, realized reason why doing because last number gets stored in newnum
last digit after being reversed , not entire number. how can rectify this??
my code
int i, remainder = 0, newnum = 0; console.writeline("enter number: "); int uinput = convert.toint32((console.readline())); (i = uinput; > 0; = (i / 10)) { remainder = % 10; console.write(remainder); newnum = remainder; } if (newnum == uinput) { console.writeline("the number {0} palindrome", uinput); } else { console.writeline("number not palidrome"); } console.writeline(uinput); console.writeline(newnum); console.readkey(); }
i looked online @ code example, thing don't understand in why num being converted boolean type in while loop? keep loop running?
the code reffered above
int num, rem, sum = 0, temp; //clrscr(); console.writeline("\n >>>> find number palindrome or not <<<< "); console.write("\n enter number: "); num = convert.toint32(console.readline()); temp = num; while (convert.toboolean(num)) { rem = num % 10; //for getting remainder dividing 10 num = num / 10; //for getting quotient dividing 10 sum = sum * 10 + rem; /*multiplying sum 10 , adding remainder*/ } console.writeline("\n reversed number is: {0} \n", sum); if (temp == sum) //checking whether reversed number equal entered number { console.writeline("\n number palindrome \n\n"); } else { console.writeline("\n number not palindrome \n\n"); } console.readline();
any sort of appreciated!! thank :)
i'm not sure you're asking, since second snippet of code found online should fix issue. code works, if change line
newnum = remainder;
to
newnum = (newnum*10) + remainder;
the issue in case not condition used in loop, it's you're overwriting newnum remainder every time, newnum storing last reminder calculated in loop, "forgetting" others had calculated before.
to reverse number, every time enter loop, should add last remainder you've found right of newnum, equivalent multiplying 10 , adding remainder.
try follow step step pen , paper (or debugger).
Comments
Post a Comment