Yêu cầu:
– Cho mảng số nguyên
– Tìm phần tử có giá trị lớn nhất trong mảng và là số chứa toàn chữ số lẻ. Nếu không tìm thấy, hàm trả về 0.
Ví dụ:
– Cho mảng nguyên A = {235, -439, 124, 678, 973}
– Phần tử có giá trị lớn nhất thỏa mãn điều kiện là: 973
Giải thuật:
– Duyệt mảng, kiểm tra từng phần tử có thỏa mãn điều kiện có giá trị lớn nhất và chứa toàn chữ số lẻ
Code
/************************************************************ * Author: VNCODING * History * 2016/12/27 first create VNCODING *************************************************************/ #include <stdio.h> #include <conio.h> #include <math.h> #define MAX_SIZE_ARR 100 bool check_all_odd_digits(int x); int get_max_with_odd_digits(int*, int); int main() { int arr[MAX_SIZE_ARR]; int n, i; int res; do { printf("n = "); scanf("%d", &n); }while(n <= 0 || n > 100); // Input array for(i = 0; i < n; i++) { printf("\narr[%d] = ", i); scanf("%d", &arr[i]); } res = get_max_with_odd_digits(arr, n); if (res == 0) { printf("\nNot found!!!"); } else { printf("\nThe maximum value with all odd digits: %d", res); } getch(); return 0; } bool check_all_odd_digits(int x) { int cnt = 0; int i, digit = 0; int temp = x; // Count the number of digit do { x /= 10; cnt++; } while (x); for (i = 0; i < cnt; i++) { digit = temp / pow(10.0, cnt-i-1); temp = temp % (int)pow(10.0, cnt-i-1); if (digit%2 == 0) { return false; } } return true; } int get_max_with_odd_digits(int arr[], int sz) { int i; int res = 0; int max = arr[0]; // Find maximum value for (i = 1; i < sz; i++) { if (max < arr[i]) { max = arr[i]; } } if (check_all_odd_digits(max)) { res = max; } return res; }
Kết quả:
Leave a Reply
You must be logged in to post a comment.