import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Handler;
import javax.swing.text.StyledEditorKit.ForegroundAction;
public class Chapter1 {
public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
System.out.print("input==>");
while ((line = br.readLine()) != null) {
if (line.trim().equals("q"))
break;
int n = 0;
try {
n = Integer.parseInt(line);
} catch (Exception e) {
System.out.println("input error");
System.out.print("input==>");
continue;
}
System.out.println("-----------handle1-----------------");
long start = System.currentTimeMillis();
System.out.println("1 total count:"+handle1(n));
System.out.println("total time:"
+ (System.currentTimeMillis() - start));
System.out.println("-----------handle2-----------------");
start = System.currentTimeMillis();
System.out.println("1 total count:"+handle2(n));
System.out.println("total time:"
+ (System.currentTimeMillis() - start));
System.out.print("input==>");
}
}
// ///////////////解法1////////////////////////
public static int handle2(int n) {
int result = 0;
for (int i = 1; i <= n; i++) {
int temp = count2(i);
result += temp;
}
return result;
}
public static int count2(int n) {
int count = 0;
while (n != 0) {
count += (n % 10 == 1) ? 1 : 0;
n /= 10;
}
return count;
}
// /////////////解法2//////////////////////////
public static int handle1(int n) {
int result = 0;
for (int i = 1; i <= n; i++) {
int temp = count1(new Integer(i).toString());
result += temp;
}
return result;
}
public static int count1(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '1')
result++;
}
return result;
}
}
输出结果:
input==>100000000
-----------handle1-----------------
1 total count:80000001
total time:11656
-----------handle2-----------------
1 total count:80000001
total time:8937
input==>