剑指 43

5 篇文章 0 订阅

题目

在这里插入图片描述

思路

1.最高位1出现的次数
	如果最高位为1,那么出现次数就是后4位的值 + 1
			不为1,那么出现次数就是10^(10的后4位)
2.后几位出现的1的次数,最高位的值 * 后几位的排列组合(位数 * 10^位数-1 )

题解

class Solution {
    public int countDigitOne(int n) {
        return getCount(String.valueOf(n), 0);
    }

    private int getCount(String str, int count) {
        if (str == null || Integer.valueOf(str) == 0) {
            return count;
        }
        if (Integer.valueOf(str) < 10) {
            return count + 1;
        }
        // n = 25654  0-5654  5655-25654
        // 位数
        int length = str.length();
        // 最高位的值
        int first = str.charAt(0) - '0';
        int highCount = 0;
        int lowCount = 0;
        if (first == 0) {
            return getCount(str.substring(1), count);
        } else if (first == 1) {
            highCount = Integer.valueOf(str.substring(1)) + 1;
        } else {
            highCount = Double.valueOf(Math.pow(10, length - 1)).intValue();
        }
        lowCount = first * (length - 1) * Double.valueOf(Math.pow(10, length - 2)).intValue();
        count += (highCount + lowCount);
        return getCount(str.substring(1), count);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值