首页 > 编程语言 > 详细

leetcode踩坑记录-求解数组中数字位数为偶数的个数

时间:2021-08-11 09:34:33      阅读:21      评论:0      收藏:0      [点我收藏+]

Given an array nums of integers, return how many of them contain an even number of digits.

Example:Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.

最初的想法直接使用\(\lg x\)解决问题,但是结果发现计算机毕竟是2进制的,无法进行准确的计算,具体错误可以参考如下代码:

#include<cmath>
#include <string>
#include <iostream>
class Solution {
public:
    int findNumbers(vector<int>& nums) {
        int count = 0;
        for(int i = 0;i < nums.size(); i++){
            if(isEvenNumber(nums[i])){
                count++;
            }
        }
        
        return count;
    }
    
    // is even?
    bool isEvenNumber(int num){
        int res = (int)((log(num)/log(10)) + 1.0); // 此处如果num=1000,res=3,就是因为实际上准确度是达不到的

        if(res%2 == 0)  
            return true;
        else
            return false;
    }

    // 直接转换为字符串
    bool isEvenNumber(int num){
        string snum = std::to_string(num) ;
        int res = snum.size();

        if(res%2 == 0)  
            return true;
        else
            return false;
    }
};

leetcode踩坑记录-求解数组中数字位数为偶数的个数

原文:https://www.cnblogs.com/qiuyeruolan/p/15126240.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!