日期:2014-05-20  浏览次数:20762 次

java基础题
对于一个整数n,有一个函数f(n) 可以计算到0到n之间的出现“1“的个数。
  例如:f(1) = 1,f(13) = 6,
  因为 1,2,3,4,5,6,7,8,9,10,11,12,13 数数1的个数正好是6。
 实现这个函数 int f(int n) 
 只能用递归解答!
请高手指点一下!

------解决方案--------------------
Java code

public static int test(int i) {
        if (1 == i) {
            return 1;
        }
        return (String.valueOf(i).indexOf("1") == -1 ? 0 : 1) + test(i - 1);
    }

    public static void main(String[] args) {
        System.out.println("包含1个数: " + test(13));
    }

------解决方案--------------------
Java code

import java.util.Scanner;

public class OneCount {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        System.out.println(count(n));
    }

    private static int count(int n) {

        if (0 >= n) {
            return 0;
        } else {
            return count(n-1) + getOneCount(n);
        }
    }

    private static int getOneCount(int n) {

        int count = 0;
        String str = String.valueOf(n);
        for (int i = 0; i < str.length(); i++) {
            if('1' == str.charAt(i))
                count++;
        }
        return count;
    }

}

------解决方案--------------------
用递归,效率太低了,这个有个规律的

C/C++ code

#include <iostream>
using namespace std;

int main()
{
    int num = 121212,saveNum = 1,countNum = 0,lastNum=0,numCopy = num;
        while(num!=0)
       {
        lastNum = num%10;
      num/=10;
    if(lastNum == 0){
      countNum +=(num)*saveNum;
    }else if(lastNum == 1){
      countNum += num * saveNum + numCopy%(saveNum) + 1;
    }else{
      countNum +=(num+1)*saveNum;
    }
      saveNum*=10;
    }
    cout<<countNum<<endl;
    return 0;
}

------解决方案--------------------
Java code
public class CountOnes {
    
    private static int getCount(int number) {
        if ((number !=0 ) && ((number % 10) == 1))  {
            return (getCount(number / 10) + 1);
        } else if ((number !=0 ) && ((number % 10) != 1)) {
            return getCount(number / 10);
        } else {
            return 0;
        }
    }
    
    private static int calcCountNumber(int number) {
        int result = 0;
        for (int i = 0; i < (number + 1); i++) {
            result += getCount(i);
        }
        return result;
    }
    
    public static void main(String [] args) {
        System.out.println(calcCountNumber(13));
    }
}