如何求偶数位置上元素的和
How to find the sum of elements on even position?
如何在不使用数组等的情况下,只进行正常操作的情况下找到偶数位置上的元素之和?
例如: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函数的其他方法。但这是留给读者的练习。
相关文章:
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 求最大元素位置的分治算法
- 如何将元素添加到向量的字符串位置
- 这个返回元素位置的基于循环的函数有什么问题?
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 数组中所有元素的最新最小元素的第五个位置
- 是否有任何优雅的方式来遍历元素位置可以更改的列表?
- 如何从几乎排序的链表中分离放错位置的元素?
- 如何获得相同数量的第一个和第二个元素以及它们在c++中各自的位置
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- 这是查找向量中元素位置的合法方法吗?
- 用于在字符串(C )向量中找到元素位置的函数中的错误
- 如何比较和存储 2 个向量的数据元素位置
- 获取与特定模式距离最小的矢量的元素位置
- 最大 N 个等元素位置的 C++ 向量
- OpenCV 从矩阵中获取条件基最大元素位置
- 有没有一种方法可以从传递给排序的lambda中获取元素位置
- 标准::多集,跟踪插入的元素位置
- 在C++中指定数组声明中的元素位置
- 获取std::vector中的元素位置