Cho một số N với chúng ta phải tích số có chữ số lẻ lớn nhất của nó. Nếu không có chữ số lẻ thì in -1.
Giống như chúng ta đã khởi tạo N bằng “153” và chữ số lẻ lớn nhất trong số này là 5 nên kết quả sẽ là tích của 153 với 5, tức là 153 * 5 =765 và nếu số không có chữ số lẻ như 246 thì kết quả phải là -1.
Đầu vào - N =198
Đầu ra - 1782
Giải thích - 198 * 9 =1782
Đầu vào - N =15382
Đầu ra - 76910
Giải thích - 15382 * 5 =76910
Phương pháp tiếp cận được sử dụng bên dưới như sau để giải quyết vấn đề -
-
Lấy đầu vào N.
-
Duyệt qua từng chữ số và tìm các chữ số lẻ
-
Tìm phần tử lẻ lớn nhất.
-
Tích số phần tử tắt lớn nhất với số ban đầu N.
-
Nếu không có kết quả cập nhật phần tử lẻ nào bằng -1.
-
Trả lại kết quả.
Thuật toán
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
Ví dụ
#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;
} Đầu ra
Nếu chạy đoạn mã trên, nó sẽ tạo ra kết quả sau -
109459