您的位置:首页 > 其它

1的数目问题

2015-06-21 21:45 323 查看
1.题目:

给定一个十进制的正整数,写下从1开始,到N的所有整数,然后数一下其中出现“1”的个数。

要求:
写一个函数 f(N) ,返回1 到 N 之间出现的 “1”的个数。例如 f(12) = 5。
在32位整数范围内,满足条件的“f(N) =N”的最大的N是多少
思路
最初看见这个问题我感觉这个有规律的问题 肯定是存在了特殊的数字,包含着规律于是我想找到特殊数字于是我找到13

N=13 f(N)=2+4=6;
N=23 f(N)=3+10=13;

package yunsuan;

import org.junit.Test;

public class find1 {

public int Count(int n){
int count = 0;
int  n1 = 1;
int nN = 0;
int gN = 0;
int hN = 0;
if (n <= 0){
return 0;
}
while (n / n1 != 0){
nN = (n - (n / n1)*n1);
gN =  ((n / n1) % 10);
hN =  (n / (n1 * 10));
if (gN == 0){
count += hN*n1;
}
else if (gN == 1){
count += hN*n1 + nN + 1;
}
else
{
count += (hN + 1)*n1;
}
n1 *= 10;
}
return  count;
}

@Test
public void fun(){

int i;
for (i = 0; i < 2147483647; i++)
{
if (Count(i) == i)
{
System.out.println(i);
}
}

}

}




N=33 f(N)=4+10=14;
.......
N=93 f(N)=10+10=20
发现这个规律
运行截图:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: