aboutsummaryrefslogtreecommitdiff
path: root/num_even_nums.cpp
blob: 5d5c2400cb5b952515d2e3146bc83ceec095d74e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include "leetcode.h"

/*
 * given array 'nums' of integers, return how
 * many of them contain an even number of digits.
 */

class Solution {
public:
  int findNumbers(vector<int> &nums) {
    int ans = 0;
    // use auto to identify data type & iterate through array
    for (auto i : nums)
      /*
       * log10 returns a decimal so convert it to int
       * it also returns n - 1. eg. log10(100) = 2
       * use bitwise and to check if it's odd
       */
      ans += (int)log10(i) & 1;
    return ans;
  }
};

int main() {
  Solution obj;
  vector<int> nums1 = {12, 345, 2, 6, 7896}, nums2 = {555, 901, 482, 1771};
  cout << obj.findNumbers(nums1) << endl; // expect: 2
  cout << obj.findNumbers(nums2) << endl; // expect: 1
}