取巧思路,既然数值本身没有意义,那就转成字符串拼接到一起,遍历字符串
缺点:虽然思路简单,但时间空间耗费大
public class Solution { static int num = 0; static String s_result; public int NumberOf1Between1AndN_Solution(int n) { //遍历1-n,z转成字符串接到s_result上 for (int i = 0; i <= n; i++) { s_result = s_result + i; } //遍历s_result,如果==‘1’,则计数加一 for (int i = 0; i < s_result.length(); i++) { if(s_result.charAt(i)=='1'){ num++; } } return num; } }
优化一下,会好一些
public class Solution { public int NumberOf1Between1AndN_Solution(int n) { int num=0; //遍历1-n,z转成字符串接到s_result上 for (int i = 0; i <= n; i++) { String s_result=i+""; //再遍历当前字符串,即当前数字,更新1的数量 for (int j = 0; j <s_result.length() ; j++) { if(s_result.charAt(j)=='1'){ num++; } } } return num++; } }