Yêu cầu:
– Cho mảng số nguyên
– Tìm phần tử đầu tiên trong mảng nguyên có chữ số đầu là lẻ. Nếu không tìm thấy, hàm trả về 0.
Ví dụ:
– Cho mảng nguyên A = {234, -439, 124, 678, 973}
– Phần tử đầu tiên trong mảng có chữ số đầu lẻ là 124
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 chữ số đầu là lẻ không?
Code
/************************************************************ * Author: VNCODING * History * 2016/12/24 first create VNCODING *************************************************************/ #include <stdio.h> #include <conio.h> #include <math.h> #define MAX_SIZE_ARR 100 bool check_first_digit(int x); int get_first_odd_digit(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_first_odd_digit(arr, n); if (res == 0) { printf("\nNot found!!!"); } else { printf("\nThe first element has odd first digit is: %d", res); } getch(); return 0; } bool check_first_digit(int x) { int cnt = -1; int temp = x; // count the number of digit do { x /= 10; cnt++; }while(x); // get first digit of x temp = temp / (int)pow(10.0, (double)cnt); // check first digit is odd or even if (temp % 2) // odd number { return true; } else // even number { return false; } } int get_first_odd_digit(int arr[], int sz) { int i; int res = 0; for (int i = 0; i < sz; i++) { if (check_first_digit(arr[i])) { res = arr[i]; break; } } return res; }
Kết quả:
Leave a Reply
You must be logged in to post a comment.