日期:2014-05-20 浏览次数:20762 次
public static int test(int i) { if (1 == i) { return 1; } return (String.valueOf(i).indexOf("1") == -1 ? 0 : 1) + test(i - 1); } public static void main(String[] args) { System.out.println("包含1个数: " + test(13)); }
------解决方案--------------------
import java.util.Scanner; public class OneCount { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); System.out.println(count(n)); } private static int count(int n) { if (0 >= n) { return 0; } else { return count(n-1) + getOneCount(n); } } private static int getOneCount(int n) { int count = 0; String str = String.valueOf(n); for (int i = 0; i < str.length(); i++) { if('1' == str.charAt(i)) count++; } return count; } }
------解决方案--------------------
用递归,效率太低了,这个有个规律的
#include <iostream> using namespace std; int main() { int num = 121212,saveNum = 1,countNum = 0,lastNum=0,numCopy = num; while(num!=0) { lastNum = num%10; num/=10; if(lastNum == 0){ countNum +=(num)*saveNum; }else if(lastNum == 1){ countNum += num * saveNum + numCopy%(saveNum) + 1; }else{ countNum +=(num+1)*saveNum; } saveNum*=10; } cout<<countNum<<endl; return 0; }
------解决方案--------------------
public class CountOnes { private static int getCount(int number) { if ((number !=0 ) && ((number % 10) == 1)) { return (getCount(number / 10) + 1); } else if ((number !=0 ) && ((number % 10) != 1)) { return getCount(number / 10); } else { return 0; } } private static int calcCountNumber(int number) { int result = 0; for (int i = 0; i < (number + 1); i++) { result += getCount(i); } return result; } public static void main(String [] args) { System.out.println(calcCountNumber(13)); } }