演算法題:1的數目
阿新 • • 發佈:2018-10-31
給定一個十進位制正整數N,寫下從1開始,到N的所有正整數,然後數一下其中出現的所有“1”的個數。例如:N =12,我們會寫下1,2,3,4,5,6,7,8,9,10,11,12。這樣1出現的個數為5
java程式碼實現
執行結果:請輸入一個正整數N:public class demo1 { public static void main(String[] args) { Sum sum = new Sum(); System.out.println("請輸入一個正整數N:"); int v = new Scanner(System.in).nextInt(); System.out.println("從1開始,到N的所有整數,1出現的個數:" + sum.sum1(v)); } } class Sum{ public int sum1(int n){ int count = 0; int factor =1; int lowerNum = 0; int currNum = 0; int higherNum = 0; while(n/factor !=0){ lowerNum = n-(n/factor)*factor; currNum = (n/factor)%10; higherNum = n/(factor*10); switch(currNum){ case 0: count +=higherNum*factor; break; case 1: count +=higherNum*factor+lowerNum+1; break; default: count +=(higherNum+1)*factor; break; } factor *=10; } return count; } }
256
從1開始,到N的所有整數,1出現的個數:156