如何求偶数位置上元素的和

How to find the sum of elements on even position?

本文关键字:元素 位置 何求偶      更新时间:2023-10-16

如何在不使用数组等的情况下,只进行正常操作的情况下找到偶数位置上的元素之和?

例如:159

总和=5。

159120

总和=5+1+0=6。

我的作品:

int sumofdigits(int x)
{
    int sum = 0;
    while(x > 0){
        if (x % 100 != 0)
            sum += x % 100;
        x /= 100;
    }
    return sum;
}

由于您从左边开始计算"偶数"位数,因此您首先需要计算位数,以便知道最低有效位数是否为偶数:

int sumOfEvenDigits(int x)
{
    // First, count the number of digits
    int digitCount = 0;
    int tmp = x;
    while(tmp) {
        tmp /= 10;
        digitCount++;
    }
    // If the number of digits is odd, throw away the least significant digit
    if(digitCount % 2 == 1)
        x /= 10;
    // Keep adding the least significant digit, and throwing away two digits until you're done.
    int sum = 0;
    while(x){
        sum += x % 10;
        x /= 100;
    }
    return sum;
}
int accumulateIfEvenPos(int num, int pos) {
    if (num == 0) return 0;
    int digit = num % 10;
    int next = num / 10;
    return pos & 1 ? digit + accumulateIfOdd(next, ++pos) : accumulateIfOdd(next, ++pos);
}

你最初称之为pos 1-在这里演示。

简单的修改就可以了。

int main()
{
    int x = 1549;
    //Get the number of digits
    int length = snprintf(NULL, 0, "%i", x);
    int sum = 0;
    while(x > 0){
        if (x % 100 != 0) {
            //check if the number of digits is even to start from the last digit
            if (length % 2 == 0) {
                sum += x % 10;
                x /= 10; 
            }
            else {
                x /= 10;
                sum += x % 10;
            }
            x /= 10;
        }
    }
   cout << sum << endl; 
   return 0;
}

编辑:解决了算法中的问题/错误。这可能不是最好的答案,但我不想写一个完全不同的答案(与编辑前的答案不同)。

您需要一个跟踪位置的索引变量:

unsigned int digit_position = 0;
while (x > 0)  
{  
  unsigned int digit_value = x % 10;
  if (digit_position is even)
  {
     // Add digit_value to sum
  }
  // Shift value right one digit
  x /= 10;
  ++digit_position;
}

可以存在使用位置变量和CCD_ 1函数的其他方法。但这是留给读者的练习。