题目 Consider a function which, for a given whole number n, returns the number of ones required when writing out all numbers between 0 and n. For example, f(13)=6. Notice that f(1)=1. What is the next largest n such that f(n)=n? 解析 这道题的重在效率,比如要计算f(101),只要把原来的f(1)到f(100)的值都存下来,然后再加上101中1的个数就好啦 代码 public class Main{ public static void main(String[] args) { int n = 2; //从f(2)开始算起 int res =1; //因为getOnly(1)=1,所以初始值设为1 while((getOnly(n)+res)!=n){ res+=getOnly(n); ++n; } System.out.println(n); } /** * * 返回num中有多少个1(如101种有2个) */ static int getOnly(int num){ int number=0; String s = num+""; int len = s.length(); if(0!=len){ for(int i=0;i<len;i++){ char a = s.charAt(i); if(a=='1'){ number++; } } } return number; } }