---
title: "求1~N中1出现的次数的递归算法"
author: "Eastsun"
date: "2007-03-14T17:02:36Z"
tags: []
slug: "1-n-1"
draft: false
lastmod: "2007-03-14T17:02:36Z"
id: 59836
url: "https://eastsun.iteye.com/blog/59836"
---

在网上看到的一个算法题，据说是某个大公司的面试题。题目如下:给出一个数n，求1到n这些数中1出现的次数

       这个题是典型的用递归算法来解决的，代码如下：

java 代码

01. import  java.math.BigInteger;
02. import  java.util.\*;
03. /\**
04. \*求1到N这些数中1出现的次数
05. \*@author Eastsun
06. \*/
07. public   class  CountOne{
08. private   static  HashMap result = new  HashMap();
09. //计算countOne(10^n-1)
10. private   static  BigInteger computeX(String num){
11. BigInteger r =result.get(num.length());
12. if (r== null ){
13. r =countOne(num);
14. result.put(num.length(),r);
15. }
16. return  r;
17. }
18. //得到一个表示10^n的BigInteger
19. private   static  BigInteger getInteger( int  n){
20. StringBuilder sb = new  StringBuilder(n+ 1 );
21. sb.append(' 1 ');
22. for ( int  i= 0 ;i0 ');
23. return   new  BigInteger(sb.toString());
24. }
25. //生成一个代表10^n-1的字符串,即n个9
26. private   static  String getString( int  n){
27. StringBuilder sb = new  StringBuilder(n);
28. for ( int  i= 0 ;i9 ');
29. return  sb.toString();
30. }
31. /\**
32. \*计算从1到num这些数中1出现的次数
33. \*@param num 一个表示整数的字符串
34. \*/
35. public   static  BigInteger countOne(String num){
36. if (num.length()== 1 ){
37. if (num.equals( "0" ))  return  BigInteger.ZERO;
38. else                  return  BigInteger.ONE;
39. }
40. BigInteger high,lower,remainder;
41. if (num.charAt( 0 )==' 0 ') high =BigInteger.ZERO;
42. else   if (num.charAt( 0 )==' 1 ') high = new  BigInteger(num.substring( 1 )).add(BigInteger.ONE);
43. else   high =getInteger(num.length()- 1 );
44. lower =computeX(getString(num.length()- 1 )).multiply( new  BigInteger(num.substring( 0 , 1 )));
45. remainder =countOne(num.substring( 1 ));
46. return  high.add(lower).add(remainder);
47. }
48. public   static   void  main(String\[] args){
49. long  currentTime =System.currentTimeMillis();
50. BigInteger bi = new  BigInteger( "453454583828382932382932342342342423" );
51. for ( int  n= 0 ;n&lt; 10 ;n++){
52. System.out.println(bi + " :" +countOne(bi.toString()));
53. bi =bi.add(BigInteger.ONE);
54. }
55. long  det =System.currentTimeMillis() -currentTime;
56. System.out.println(det);
57. }
58. }

          注意代码里面用到了一个HashMap来保存10^n-1那些数的对应值，这段代码比较重要，如果不要的话，算法的时间复杂度将达到 O(N^(1/3)) (精确的说:其中n的指数是ln2/ln10 ) ；而加上后，算法的时间复杂度降低到O(logN).