Calculating the sum of all odd array indexes

后端 未结 5 991
予麋鹿
予麋鹿 2021-01-24 19:00

I want to calculate the sum of all odd array indexes, but I\'m having some trouble finding the right way to do it.

Here\'s my code so far:

    String id         


        
5条回答
  •  难免孤独
    2021-01-24 19:47

    The other answer is right, you are only looping to 5. However, you're making this overly complicated; there's a neat trick you can use to avoid Integer.parseInt() and String.valueOf():

    int sum = 0;
    
    for (int i = 1; i < id.length(); i += 2) {
        sum += (id.charAt(i) - '0');
    }
    

    Also note that instead of checking i%2 repeatedly, you can simply add 2 to the loop control variable at the end of each iteration (and let it start at 1 so you hit only the odd indices).

提交回复
热议问题