计算1的个数——编程之美

来源:互联网 发布:数据安全人员工作职责 编辑:程序博客网 时间:2024/06/05 07:57

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

N = 2; 只有一个1

N= 12;只有五个1, 1 、、、10,11,12。

分析:

一,从1开始遍历到N,将中每一个书中含有1的个数加起来。

方法如下:

static int countOneInInt(int n) {int num = 0;while(n != 0) {num = num + (n % 10 == 1 ? 1 : 0);n = n / 10;}return num;}static int countAllOnes(int num) {long startTime = System.currentTimeMillis();int sum = 0;for (int i = 1; i <= num; i++) {sum = sum + countOneInInt(i);}System.out.println("countAllOnes const time: " + (System.currentTimeMillis() - startTime));return sum;}

但是此方法要遍历所有小于N的数,在效率上存在问题。

二,通过分析“小于N的输在每一位上可能出现1的次数”

先看1位数的情况。

如果N = 3; 1次        N 》 = 1,f(N) = 1           如果N = 0;则f(N)为0;

再看2位数情况 

N= 13 : 1 , 10, 11, ,12, 13    f(N) = 2(个) + 4(十) = 6;

N= 23: 1, 10 、、、19, 21    f(N) = 3 + 10 = 13;

通过对两位数分析:

1,个位出现1的次数 与个位,十位数有关。当个位上的数大于等于1 则出现一的次数等于十位数上的数字加1;如果个位上的数等于0,则个位上出现1的个数为十位上的数字。

2,十位出现1的次数            如果十位上的数字为1,则十位上出现1的个数为个位数字加1; 如果十位数大于1,这十位上出现1的次数为 10;

f(33) = 4 + 10 = 14;

f(43) = 5 + 10 = 15;

、、、

f(93) = 10 + 10 = 20;


分析更多位数得到如下结论:

如果百位上德尔数字为0,百位上出现1的次数有更高位决定  更高位数字 * 当前位数(类似权重:十位,百位、、、);

如果百位上的数字为1,百位上出现1的次数不仅受高位,还受地位影响 更高位数字 *当前位数 + (地位数字 + 1);

如果百位上的数字大于1,则百位出现1的次数仅由更高位决定 (更高位数字 + 1) × 当前位数。

相关代码如下:

static int countOne(int n) {long startTime = System.currentTimeMillis();int iCount = 0;int iFactor = 1;int iLowerNum = 0;int iCurrNum = 0;int iHeigherNum = 0;while(n / iFactor != 0) {iLowerNum = n - (n / iFactor) * iFactor;iCurrNum = (n / iFactor) % 10;iHeigherNum = n / (iFactor * 10);switch (iCurrNum) {case 0:iCount = iCount + iHeigherNum * iFactor;break;case 1:iCount = iCount + iHeigherNum * iFactor + (iLowerNum + 1);break;default:iCount = iCount + (iHeigherNum + 1) * iFactor;break;}iFactor = iFactor * 10;}System.out.println("countOne const time: " + (System.currentTimeMillis() - startTime));return iCount;}

运行结果如下:

public static void main(String[] args) {System.out.println("请输入数字n: ");Scanner scan = new Scanner(System.in);int n = scan.nextInt();System.out.println("First function: " + countAllOnes(n));System.out.println("Second function: " + countOne(n));}


请输入数字n: 111111111countAllOnes const time: 16663First function: 100000008countOne const time: 0Second function: 100000008

由运行结果就可以看出有效率的问题。

还有个人体会就是:想的越多,代码越少。所以遇到问题要多想想。

原创粉丝点击