# Iterate through a number starting at the end and adding every other digit

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
3 replies [Last post]
Never2L8
Offline
Joined: 2013-02-19

Hello,

This is my first post, and I'd consider my knowledge of Java to be virtually nonexistent. I know a little, but I'm having some trouble with the logic and the syntax of an exercise.

Hopefully, I explained the gist of the problem in the subject, but I will try to rephrase it in case it was unclear.

Ok, so let's say I have a string.

Scanner in = new Scanner(System.in);

String str = "12345678"; // I want to read the string as an int
in.next( ); // I think that converts the string into an int, is that correct?; is it in.next(), or in.nextInt(), or maybe even in.nextLine()

// That's part 1 - if I use the Scanner class what method will convert a String to an int?

Now, I want to go to the end of the String/int "12345678", starting at the end of the, I'll call it, an int, and starting with the last digit, count backwards, skip every other digit and finally add all of the digits together.

In other words, I want to take String str = "12345678"; convert that to the integer 12345678, go to the end of the line, and iterate backwards through the line starting at 8. It would be 8642, but I want to add them, so it would be 8 + 6 + 4 + 2.

Thanks; I'm sorry if I rambled on there, I just wanted to be sure I was clear.

Any help would be appreciated!

Have a good one!

phil1234
Offline
Joined: 2011-07-15

Using in.NextInt(), you would read the bit before the next token as an Integer.
The following code will calculate the sum of the digits of an Integer num:

``int num = 12345;int sum = 0;		while(num > 0) {	sum += num % 10;	num /= 10;}``

num % 10 will always give you the last digit of num. By dividing num by 10, you get rid of the last digit.

Hope that helped.

Never2L8
Offline
Joined: 2013-02-19

Actually, it did help, the first part, at least. The code is pretty cool. At first, I didn't really understand it, so I had to write it out.

First pass through the loop, sum = 5; num = 5;
Second pass, sum = 9; num = 4;
Third pass, sum = 12; num = 3;
Fourth pass, sum = 14; num = 2;
Fifth pass, sum = 15; num = 1;

But, let's say I didn't want to include every digit; let's say the number was larger, and I wanted to skip the second pass, and the fourth pass, and the sixth pass, eighth, tenth ... in other words, every other integer would be skipped. So, in the example, I'd want to calculate the one's place or pass one, the 100's place or pass three, the 10000's place or pass five, and so forth.

Thank you very much by the way. Very cool loop; I appreciate it. I'm eager to learn anything else you might offer.

phil1234
Offline
Joined: 2011-07-15

``for(int i = 0; num > 0; i++){    if(i%n == 0)    {        sum += num % 10;    }    num /= 10;}``