给定一个整数n,返回从1到n的数字中1出现的个数。
例如:
为那么1出现了1次,所以返回1。
为那么1出现的次数为1(出现1次),10(出现1次),11(有两个1,所以出现了2次),所以返回4。
https://blog.csdn.net/yi_Afly/article/details/52012593?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1&utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1 这篇博客讲的很清楚,然后要注意10的13次超出了int的表示范围 import java.util.Scanner; /* * * https://www.nowcoder.com/practice/38af9b5a06ea4448ae9b2a488b6a991f?tpId=101&&tqId=33140&rp=1&ru=/activity/oj&qru=/ta/programmer-code-interview-guide/question-ranking * * */ public class Main { public static long count(long n) { if (n < 1) { return 0; } long count = 0; long round = n; long weight = 0; long base = 1; while (round > 0) { weight = round % 10; round = round / 10; count += round * base; if (weight == 1) { count += n % base + 1; } else if (weight > 1) { count += base; } base *=10; } return count; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); System.out.println(count(n)); } }
#include<iostream> #include<algorithm> using namespace std; int main(){ long long N; while(cin>>N){ long long base=10; long long mul=1; long long count=0; do{ count+=(N/base)*mul; if(N%base+1-1*mul>=0) count+=min(N%base+1-1*mul,mul); mul*=10; base*=10; }while(N*10>=base); cout<<count<<endl; } return 0; }
思路:分别统计k出现在个位,十位,百位,千位...的个数。
并给出一个通用解法:
1-n中,出现数字k的次数是多少。
left记录对于当前位的高位
right记录对于当前位的低位
当前位还用分:k三种情况讨论
参考:https://blog.csdn.net/qq_25024883/article/details/80337312
n = 2593, x = 5 为例来解释如何得到数学公式。从 1 至 2593中,数字 5 总计出现了 813 次,其中有 259次出现在个位,260次出现在十位,294次出现在百位,0次出现在千位。
n = int(input()) k = 1 l = [] res = 0 tmp = 1 while tmp < n: left = n // (tmp * 10) right = tmp res += left * right if n % (tmp * 10) // tmp > k: res += right if n % (tmp * 10) // tmp == k: res += n % tmp + 1 tmp *= 10 print(res)