ให้ตัวเลข 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\n", findproduct(n));
return 0;
} ผลลัพธ์
หากรันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
109459