N在C中具有最大奇数的乘积
给定数字N,我们必须乘以其最大的奇数位。如果没有奇数,则打印-1。
就像我们用“153”初始化N一样,该数字中最大的奇数是5,因此结果将是153与5的乘积,即153*5=765,如果该数字没有像246这样的奇数,则输出必须为-1。
输入-N=198
输出-1782
说明-198*9=1782
输入-N=15382
输出-76910
说明-15382*5=76910
以下使用的方法来解决问题-
取输入N。
遍历每个数字并查找奇数数字
找到最大的奇数元素。
用原始编号N乘积最大的off元素。
如果没有奇数元素,则更新结果为-1。
返回结果。
算法
Start
In function int largestodd(int n)
Step 1→ Declare and Initialize large as -1
Step 2→ Loop While n > 0
Set digit as n % 10
If digit % 2 == 1 && digit > large then,
Set large as digit
Set n as n / 10
Step 3→ Return large
In function int findproduct(int n)
Step 1→ Declare and Initialize large set largestodd(n)
Step 2→ If large == -1 then,
Return -1
Step 3→ Return (n * large)
In function int main() Step 1→ Initialize n as 15637
Print the results from calling findproduct(n)
Stop示例
#include <stdio.h>
int largestodd(int n){
//如果所有数字都是偶数
//我们将返回-1-
int large = -1;
while (n > 0) {
//从最后一位开始检查
int digit = n % 10;
//如果当前数字为奇数,并且
//大于大
if (digit % 2 == 1 && digit > large)
large = digit;
n = n / 10;
}
//返回最大值
//n的奇数位
return large;
}
int findproduct(int n){
int large = largestodd(n);
//如果n中没有奇数位
if (large == -1)
return -1;
//具有最大奇数的n的乘积
return (n * large);
}
int main(){
int n = 15637;
printf("%d\n", findproduct(n));
return 0;
}输出结果
如果运行上面的代码,它将生成以下输出-
109459