求奇数位与偶数位数字和的差值
给定一个数字,找出奇数位数字总和与偶数位数字总和的差值。这意味着我们将计算所有偶数数字和所有奇数数字,再减去总和。
示例
Input:12345 Output:3
说明
the odd digits is 2+4=6 the even digits is 1+3+5=9 odd-even=9-6=3
将每个数字从数字中取出,检查数字是偶数还是奇数,如果是偶数,则将其添加到偶数总和中,如果不是,则将其添加到奇数总和中,然后取它们的差值。
示例
#include <iostream>
using namespace std;
int main() {
int n, r=0;
int diff =0;
int even=0;
int odd=0;
n=12345;
while(n != 0){
r = n%10;
if(r % 2 == 0) {
even+=r;
} else {
odd+=r;
}
n/=10;
}
diff=odd-even;
printf("%d",diff);
return 0;
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP