java循环(缓存机制)

1、有一个整数n,写出一个函数f(n),返回0~n之间出现的“1”的个数。比如f(1)=1;  f(13) = 6,(1,10,11,12,13总共含有6个1)。问满足f(n)=n的n是多少?

 1 public class Test {
 2 
 3     public static void main(String[] args) {
 4         int n = 2;
 5         int res = 1;
 6         while((getOnly(n)+res) != n){
 7             res += getOnly(n);        //res中保存着到n为止,已经有几个n
 8             ++n;
 9         }
10         System.out.println(n);
11     }
12 
13     static int getOnly(int num) {    //计算n中含有几个1
14         int number = 0;
15         String s = num + "";
16         int len = s.length();
17         if(len != 0){
18             for(int i=0;i<len;i++){
19                 char a=s.charAt(i);
20                 if(a == '1'){
21                     number++;
22                 }
23             }
24         }
25         return number;
26     }
27 }

输出结果为199981

原文地址:https://www.cnblogs.com/XuGuobao/p/7240864.html