Home > Enterprise >  How can I iterate through a long starting from the second to last digit?
How can I iterate through a long starting from the second to last digit?

Time:10-05

I figured out how to iterate through the long starting from the last digit and add up every other digit (shown below). I am unsure how to do it starting from the second to last digit (in this case, starting from 2).

long digit = 048231312623;
long sum = 0;
// Iterate through digit from the end
        while (digit > 0) {
            sum  = digit % 10;
            digit /= 100;
            System.out.print(sum   " "); // checking if correctly iterates
        }

CodePudding user response:

You said add every other digit. That sounds like you want to skip a digit in between. If so, do it as below. If you want to just ignore the last digit and sum the rest, change val/=100 to val/=10.

To add up every other digit after the last, you must first expose the last digit by dividing by 10. Then use the remainder operator to retrieve the digit. To expose the next digit to sum(i.e skipping one), divide by 100.


long val = 929032199374023L;
int sum = 0;
val/=10; // skip last to start, expose next to last.
while(val != 0) {
    sum  = val;
    System.out.println("adding "   val); // for verification
    val/=100; // expose next digit
}
System.out.println("\nsum = "   sum);

prints

adding 2
adding 4
adding 3
adding 9
adding 2
adding 0
adding 2

sum = 22

CodePudding user response:

You can divide the digit by 10 and for the next number by the 10 to the power of the position:

x = digit / (10^y) * 10

Where x is the result you want, and y is the amount of trailing numbers you want to remove minus one.

long digit = 123L;
        String valueOf = String.valueOf(digit);

        for(int i = 1; i<=valueOf.length(); i  ){
            System.out.println((long) (digit/(Math.pow(10,i))*(10)));
        }

This will print: 123, 12, 1 (and of course you can save it in a variable too)

I hope this makes sense.

  •  Tags:  
  • java
  • Related