04 Find Numbers with Even Number of Digits

关注 每天一道编程题 专栏,一起学习进步。

题目

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

Example 1:

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.

Example 2:

Input: nums = [555,901,482,1771]
Output: 1
Explanation:
Only 1771 contains an even number of digits.

Constraints:

1 <= nums.length <= 500
1 <= nums[i] <= 10^5

分析

给一串数组,返回里面位数为偶数的数据个数。
就是
判断“移动多少位小数点使其小于0”
==>判断除以多少次“10”能使其小于0

解答

class Solution {
    public int findNumbers(int[] nums) {
        int result=0;
        for(int num:nums){
            int sum=0;
            while(num>0){
                num/=10;
                sum++;
            }
            if(sum%2==0)
                result++;
        }
        return result;
    }
}

在这里插入图片描述

其他答案

更新奇

题目中已经给出限制:
1 <= nums[i] <= 10^5
也就是说:
10~99—偶数位
1000~9999—偶数位置
100000 —偶数位置

因此,只需要遍历nums,判断num是否在上述两个区间之内或等于100000即可。

Nice, telling myself to pay attention to constraints.

更简洁

将数字转为String,看他的长度是否为偶数

int result=0;
for(int n: nums){
	result+= 1 - Integer.toString(n).lenght()%2;
return result;

由于取余结果要么为1(奇数),要么为0(偶数)
因此用1-取余结果

升级版

既然需要遍历,自然想到用Stream

return Arrays.stream(nums).map(i->1-Integer.toString(i).length()%2).sum();
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值