统计0到n之间1的个数
生活随笔
收集整理的這篇文章主要介紹了
统计0到n之间1的个数
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
問(wèn)題描述
給定一個(gè)十進(jìn)制整數(shù)N,求出從1到N的所有整數(shù)中出現(xiàn)”1”的個(gè)數(shù)。?
例如:N=2時(shí) 1,2出現(xiàn)了1個(gè) “1” 。
N=12時(shí) 1,2,3,4,5,6,7,8,9,10,11,12。出現(xiàn)了5個(gè)“1”。
1、暴力求解法
//暴力求解 long CountOnes(long n) {int i,j;//循環(huán)變量int ncount=0;//計(jì)數(shù)for (i=1; i<=n; i++){j=i;while(j!=0){if (j%10==1){ncount++;}j/=10;}}return ncount; }2、統(tǒng)計(jì)方法
統(tǒng)計(jì)n每一位的值:
current = (n / i) % 10;before = n / (i * 10);after = n - (n / i) * i;
123
current=2;
before=1;
after=3;
對(duì)于某個(gè)位置,它可以是大于1,等于1,等于0
如果大于1,則由高位+1決定數(shù)目
如果等于1,則由其左右兩邊的數(shù)目決定
如果等于0,也是由高位決定
1、current=0時(shí)
cout=cout+before*i;
2、current=1
cout=cout+before*i+after*i
3、current>1
cout=cout+(before+1)*i
public long CountOne2(long n) {long count = 0;long i = 1;long current = 0, after = 0, before = 0;while ((n / i) != 0) {current = (n / i) % 10;before = n / (i * 10);after = n - (n / i) * i;if (current > 1)count = count + (before + 1) * i;else if (current == 0)count = count + before * i;else if (current == 1)count = count + before * i + after + 1;i = i * 10;}return count; }
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀
總結(jié)
以上是生活随笔為你收集整理的统计0到n之间1的个数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。