C语言中求N与其最大奇数位的乘积
给定一个数字N,我们需要将这个数字与其最大的奇数位相乘。如果没有奇数位,则打印-1。
例如,如果N初始化为“153”,则该数字中最大的奇数位是5,因此结果将是153与5的乘积,即153 * 5 = 765;如果数字没有奇数位,例如246,则输出必须为-1。
输入 − N = 198
输出 − 1782
解释 − 198 * 9 = 1782
输入 − N = 15382
输出 − 76910
解释 − 15382 * 5 = 76910
下面使用的解决问题的方法如下:
获取输入N。
遍历每个数字并查找奇数。
找到最大的奇数。
将最大的奇数与原始数字N相乘。
如果没有奇数,则将结果更新为-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){
// If all digits are even then
// we wil return -1
int large = -1;
while (n > 0) {
// checking from the last digit
int digit = n % 10;
// If the current digit is odd and
// is greater than the large
if (digit % 2 == 1 && digit > large)
large = digit;
n = n / 10;
}
// To return the maximum
// odd digit of n
return large;
}
int findproduct(int n){
int large = largestodd(n);
// If there are no odd digits in n
if (large == -1)
return -1;
// Product of n with its largest odd digit
return (n * large);
}
int main(){
int n = 15637;
printf("%d
", findproduct(n));
return 0;
}输出
如果运行以上代码,将生成以下输出:
109459
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP