Java 7,74个字节(递归-包括第二个默认参数)
int c(int r,int n){r+=(n+"").length();return n>0?c(r,n-1):n<0?c(r,n+1):r;}
说明(1):
int c(int r, int n){ // Recursive method with two integer parameters and integer return-type
// Parameter `r` is the previous result of this recursive method (starting at 0)
r += (n+"").length(); // Append the result with the current number's width
return n > 0 ? // If the input is positive
c(r, n-1) // Continue recursive method with n-1
: n < 0 ? // Else if the input is negative
c(r, n+1) // Continue recursive method with n+1
? // Else (input is zero)
r; // Return the result
} // End of method
Java 7,81 79字节(循环-单个参数)
如果0
由于某种原因不允许使用默认的第二个参数作为递归方法,则可以使用如下所示的for循环:
int d(int n){String r="x";for(int i=n;i!=0;i+=n<0?1:-1)r+=i;return r.length();}
说明(2)
int d(int n){ // Method with integer parameter and integer return-type
String r = "x"; // Initial String (with length 1 so we won't have to +1 in the end)
for(int i=n; i != 0; // Loop as long as the current number isn't 0
i += n < 0 ? 1 : 1) // After every iteration of the loop: go to next number
r += i; // Append String with current number
// End of loop (implicit / single-line body)
return r.length(); // Return the length of the String
} // End of method
测试代码:
在这里尝试。
class M{
static int c(int r,int n){r+=(n+"").length();return n>0?c(r,n-1):n<0?c(r,n+1):r;}
static int d(int n){String r="x";for(int i=n;i!=0;i+=n<0?1:-1)r+=i;return r.length();}
public static void main(String[] a){
System.out.println(c(0, 8) + "\t" + d(8));
System.out.println(c(0, 101) + "\t" + d(101));
System.out.println(c(0, 102) + "\t" + d(102));
System.out.println(c(0, -10) + "\t" + d(-10));
}
}
输出:
9 9
196 196
199 199
22 22