Question

I want to calculate the digit sum & alternating digit sum (first order till third order) for a string in JAVA, but my attempt seems not to work at all ...

So for the string "123456789" ist should be:

Q1: 9+8+7+6+5+4+3+2+1 = 45
Q2: 89 + 67 + 45 + 23 + 1 = 225
Q3: 789 + 456 + 123 = 1368
AQ1: 9 − 8 + 7 − 6 + 5 − 4 + 3 − 2 + 1 = 5
AQ2: 89 − 67 + 45 − 23 + 1 = 45
AQ3: 789 − 456 + 123 = 456

unfortunately it is:

Q1: 45
Q2: 225
Q3: 1962
AQ1: -5
AQ2: 35
AQ3: -654

What's my mistake?

String zahlen = new StringBuffer(args[0]).reverse().toString();
int zahl1 = Integer.parseInt(zahlen), zahl2, zahl3;
int quersumme1 = 0, quersumme2 = 0, quersumme3 = 0;
int altquersumme1 = 0, altquersumme2 = 0, altquersumme3 = 0;
int i = 1;

zahl2 = zahl1;
zahl3 = zahl1;

while (zahl1 > 0) {
    if (i % 2 == 0) {
        altquersumme1 += zahl1 % 10;
        altquersumme2 += zahl2 % 100;
        altquersumme3 += zahl3 % 1000;
        i++;
    } else {
        altquersumme1 -= zahl1 % 10;
        altquersumme2 -= zahl2 % 100;
        altquersumme3 -= zahl3 % 1000;
        i++;
    }
    quersumme1 += zahl1 % 10;
    quersumme2 += zahl2 % 100;
    quersumme3 += zahl3 % 1000;
    zahl1 = zahl1 / 10;
    zahl2 = zahl2 / 100;
    zahl3 = zahl3 / 1000;
}

System.out.println("Q1: \t\t" + quersumme1);
System.out.println("AQ2: \t" + altquersumme1);
System.out.println("Q2" + quersumme2);
System.out.println("AQ2:\t" + altquersumme2);
System.out.println("Q3:\t\t" + quersumme3);
System.out.println("AQ3:\t" + altquersumme3);

I also tried to use a solution based on strings, but I couldn't figure out, how to adjust it to calculate the second and third order:

String zahlen = "123456789";

int quersumme = 0;

for (int counter = 0; counter < zahlen.length(); counter++) {
    int currentNumber = zahlen.charAt(zahlen.length() - counter -1) - '0';
    quersumme += currentNumber * ((counter % 2 == 0) ? 1 : -1);
}

System.out.println("quersumme: " + quersumme);
Was it helpful?

Solution

Two things to fix it:

  • Remove the String reversing.
  • Let i start at 0.

Demo working here: http://ideone.com/vbyYzQ

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top