统计数组元素位数为偶数的个数,并且将每个数组元素最大化(逢6替换成9,每个数组元素只能替换一次)
1.给定一个数组nums[],求数组nums里有多少个位数为偶数的元素,12的位数为2,456的位数为3...
2.查询含有6的数组元素,将第一个高位的6替换成9,即期望效果是456替换成459,667替换成967...
话不多说,示例代码:
#include <iostream>
using namespace std;
int main(){
int count = 0;
int nums[] = {12,456,667};
int len = sizeof(nums) / sizeof(nums[0]);
for (int i = 0; i < len; i++){
int num = nums[i];
int num1 = nums[i];
int d = 0;
if (num == 0){
d = 1;
}
while(num > 0 ){
num = num / 10;
d++;
}
cout << "当前元素" << nums[i] << "的位数为:" << d << endl;
if (d%2 == 0){
count ++;
}
int m = 0;
int a = 0;
int flag = 0;
int divisor = 1;
while (num1 / divisor >= 10){
divisor *= 10;
}
while (divisor > 0){
int digit = num1 / divisor;
cout << "替换前数值:" << digit << endl;
if (digit == 6){
if (flag == 0){
digit = 9;
flag = 1;
}
}
m = digit * divisor;
num1 = num1 % divisor;
divisor = divisor / 10;
cout << "替换后:" << digit <<endl;
a += m;
}
cout << "总数是:" << a << endl;
}
cout << "偶数位数的数组元素个数为:" << count << endl;
return 0;
}
运行效果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/5e1f5d55d32c42089655726c31d4035b.png)