LeetCode233——数字1的个数

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/number-of-digit-one/description/

题目描述:

知识点:数学

思路:PAT-ADVANCED1049——Counting Ones同样的解法

JAVA代码:

public class Solution {
    public int countDigitOne(int n) {
        int result = 0;
        if(n <= 0){
            return result;
        }
        String number = Integer.toString(n);
        for(int i = 0; i < number.length(); i++){
            if(i == 0){
                if(number.charAt(i) == '1'){
                    int right = 0;
                    for(int j = 1; j < number.length(); j++){
                        right = right * 10 + number.charAt(j) - '0';
                    }
                    result += right + 1;
                }else{
                    result += Math.pow(10, number.length() - 1);
                }
            }else if(i == number.length() - 1){
                int left = 0;
                for(int j = 0; j < number.length() - 1; j++){
                    left = left * 10 + number.charAt(j) - '0';
                }
                result += left + 1;
                if(number.charAt(i) == '0'){
                    result--;
                }
            }else{
                int left = 0, right = 0;
                for(int j = 0; j < i; j++){
                    left = left * 10 + number.charAt(j) - '0';
                }
                for(int j = i + 1; j < number.length(); j++){
                    right = right * 10 + number.charAt(j) - '0';
                }
                if(number.charAt(i) == '0'){
                    result += left * Math.pow(10, number.length() - i - 1);
                }else if(number.charAt(i) == '1'){
                    result += left * Math.pow(10, number.length() - i - 1) + right + 1;
                }else{
                    result += (left + 1) * Math.pow(10, number.length() - i - 1);
                }
            }
        }
        return result;
    }
}

LeetCode解题报告:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值