题目藐视:
常规思路:
1.编程之美解决方法:
这里写图片描述
实现代码:
import java.util.Scanner;
public class Sum1s {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
System.out.println(sum1s(n));
}
}
private static int sum1s(int n) {
// TODO Auto-generated method stub
int count = 0;//记录结果
int cur = 0; //当前位的数字
int low = 0; //低位的数字
int high = 0; //高位的数字
int factor = 1; //乘积因子
while ((n / factor) != 0) {
low = n - (n / factor) * factor;
cur = (n / factor) % 10;
high = n / (factor * 10);
switch (cur) {
case 0:
count = count + factor * high;
break;
case 1:
count = count + factor * high + low + 1;
break;
default:
count = count + factor * (high + 1);
break;
}
factor = factor * 10;
}
return count;
}
}
2. 剑指offer 解决思路:
实现代码:
import java.util.InputMismatchException;
import java.util.Scanner;
public class SumOf1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
try {
int n = in.nextInt();
System.out.println(numberOf1Between1AndN(n));
} catch (InputMismatchException e) {
// TODO Auto-generated catch block
System.out.println("请输入合法的整数");
return;
}
}
}
private static int numberOf1Between1AndN(int n) {
// TODO Auto-generated method stub
if (n <= 0) {
return 0;
}
String strN = String.valueOf(n);
return NumberOf1(strN);
}
private static int NumberOf1(String strN) {
// TODO Auto-generated method stub
int firstDigit = strN.charAt(0) - '0';
int len = strN.length();
if (len == 1 && firstDigit == 0) {
return 0;
}
if (len == 1 && firstDigit > 0) {
return 1;
}
// 假设strN 是21345
// numOfFirst 是数字10000~19999中的数字
int numOfFirst = 0;
if (firstDigit == 1) {
numOfFirst = 1 + Integer.valueOf(strN.substring(1));
} else {
numOfFirst = (int) Math.pow(10, len - 1);
}
// numOfOther 是数字1346~21345除了第一位之外的数位中的数目
int numOfOther = 0;
numOfOther = (int) (firstDigit * (len - 1) * Math.pow(10, len - 2));
// numOfRecursive 是数字1~1345中的数目
int numOfRecursive = NumberOf1(strN.substring(1));
return numOfFirst + numOfOther + numOfRecursive;
}
}
测试结果: