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