1. 程式人生 > >劍指offer程式設計題(JAVA實現)——第31題:整數中1出現的次數

劍指offer程式設計題(JAVA實現)——第31題:整數中1出現的次數



github https://github.com/JasonZhangCauc/JZOffer
  • 劍指offer程式設計題(JAVA實現)——第31題:整數中1出現的次數
  • 求出113的整數中1出現的次數,並算出1001300的整數中1出現的次數?
  • 為此他特別數了一下1~13中包含1的數字有1、10、11、12、13因此共出現6次,但是對於後面問題他就沒轍了。
  • ACMer希望你們幫幫他,並把問題更加普遍化,可以很快的求出任意非負整數區間中1出現的次數
  • (從1 到 n 中1出現的次數)。
public class Test31 {

   public static void main(String[] args) {
   	System.out.println(NumberOf1Between1AndN_Solution(5));
   	System.out.println(NumberOf1Between1AndN_Solution(13));
   	System.out.println(NumberOf1Between1AndN_Solution(0));
   	System.out.println(NumberOf1Between1AndN_Solution
(-1)); System.out.println(NumberOf1Between1AndN_Solution(1000)); System.out.println(NumberOf1Between1AndN_Solution(1)); } public static int NumberOf1Between1AndN_Solution(int n) { int count = 0; for (int i = 0; i <= n; i++) { String tmp = String.valueOf(i); char[] array =
tmp.toCharArray(); for (int j = 0; j < array.length; j++) { if (array[j] == '1') { count++; } } } return count; } /* * 此方法空間不足 * public static int NumberOf1Between1AndN_Solution(int n) { if (n < 0) { return 0; } int count = 0; int m = n; if (n == 1) { count++; return count; } if (n == 0) { return 0; } while (n >= 1) { int tmp = n % 10; if (tmp == 1) { count++; } n /= 10; } count = count + NumberOf1Between1AndN_Solution(m - 1); return count; }*/ }