package leetCode; //ch='0'的场景还没看;要进行区分下 /* 给定一个十进制正整数N,写下从1开始,到N的所有整数,然后数一下其中出现的所有“1”的个数。 以20310为例,计算百位出现1的次数,将其分为a=203,b = 10,百位的高位为20,低位为10 1、当百位数字小于1时,高位取值0-19,即高位*100 2、当百位数字等于1时,高位取值0-19,即高位*100,再加上(低位+1), 3、当百位数字大于1时,高位取值0-20,即(高位+1)*100; */ class Solution0625{ int n; char ch; Solution0625(int _n, char _ch){ this.n = _n; this.ch = _ch; } public int findCnt(){ int ret = 0; int high, low, iVal; int pow = 1; int temp = this.n; int tar = Integer.parseInt(String.valueOf(ch)); if(n < 0){ return -1; } while(temp > 0){ high = n/pow; low = n%pow; iVal = high%10; if(iVal < tar){ ret = ret + high/10*pow; }else if(iVal == tar){ ret = ret + high/10*pow + low + 1; }else{ ret = ret + (high/10+1) * pow; } System.out.println("pow:" + pow + "; ret = " + ret); temp = temp/10; pow = pow*10; } return ret; } } public class findNum { public static void main(String []args){ System.out.println("一共有" + new Solution0625(12, '1').findCnt() + "个"); } }
【一天一道】统计在从1到n的正整数中指定字符的次数
最新推荐文章于 2023-03-01 22:12:45 发布