/**
* 给定一个正整数N计算从1到N中1出现的个数
*
* @author Administrator
*
*/
public class CountOneInOneToN {
/**
* 解法1、从1到N遍历再统计1的个数
*
* @param n
* @return
*/
public int count(int n) {
int times = 0;
for (int i = 1; i <= n; i++) {
times += count1InInteger(i);
}
return times;
}
/**
* 解法2、根据规律 当前位为0:当前位出现1的次数由更高位决定:更高位*当前位数
* 当前位为1:当前位出现1的次数由更高位和地位共同决定:更高位*当前位数+(低位数字+1)
* 当前位为>1:当前位出现1的次数由更高位决定:(更高位+1)*当前位数
*
* @param n
* @return
*/
public int count2(int n) {
int count = 0;
int factor = 1;
int currentNum = 0;
int lowerNum = 0;
int higherNum = 0;
while (n / factor != 0) {
lowerNum = n - (n / factor) * factor;
currentNum = (n / factor) % 10;
higherNum = n / (factor * 10);
switch (currentNum) {
case 0:
count += higher
给定一个正整数N计算从1到N中1出现的个数
最新推荐文章于 2022-04-30 20:00:39 发布