Topic describes
Their thinking
- In this case, if violent method is used, it must time out
- The key to this question is to find a pattern
- The rule is shown in the following figure (cur>1,cur=1. Cur <1)
Solution code (simulated queue)
var countDigitOne = function(n) {
let flag = 0;
const TotalBase = Math.pow(10, (String(n).split(' ').length) - 1);
for (let i = 0; Math.pow(10,i) <= TotalBase; i++) {
let base = Math.pow(10,i);
let cur = Math.floor(n/base) % 10;
let a = Math.floor(Math.floor(n/base) / 10);
let b = n % base;
if (cur < 1) {
flag = flag + a * base;
} else if (cur > 1) {
flag = flag + (a + 1) * base;
} else {
flag = flag + a * base + b + 1; }}return flag;
};
Copy the code
Earnestly UP main
www.bilibili.com/video/av458…
Conclusion (this topic gives us the enlightenment of thinking)
- Lesson 1: Learn to solve problems by thinking of mathematical laws