java - Iterate through a number starting at the end and adding every other digit -
i working on school assignment, looking guidance on doing wrong. part of larger program, trying work on loop before implement rest of program. basically, loop suppose iterate through number , add every other number, example:
if number entered 48625, return sum of 5+6+4. figured have combine loop if statement iterate through each nth number, worked out far:
class testloop{ public static void main (string args[]){ int num = 12345; int sum = 0; for(int = 0; num > 0; i++) { if(i%num == 0) { sum += num % 10; } num /= 10; system.out.println(sum); } } }
unfortunately, not working. returns 6,5,5,5,5. not adding nth values planned.
i tried following:
int num = 12345; int sum = 0; while(num > 0) { sum += num % 10; num /= 10; }
but did not work either, returned 15, sum of digits in variable num. know close solution, it's somewhere between 2 codes, can't seem right.
int num = 12345; int sum = 0; int pos = 0; while(num > 0) { int digit = num % 10; // make blatantly clear digit if (pos % 2 == 0) sum += digit; num /= 10; pos++; }
you needed checking mechanism ensure you're skipping half digits. [you're trying add digits of number, not numbers. editor.]
this fix first solution:
if(i%2 /*not num*/ == 0)
Comments
Post a Comment