It's a little piece of cake in the neighborhood today: "How many times did 1 appear in 0~400?" ”。
Side dishes to see the majority of users to the algorithm is based on string processing, the idea is roughly: stitching all the numbers into a string, and then processing the string, and then get the number of occurrences. For example, the following code:
1 /**2 * User version3 * Find out the number of occurrences of "1"4 **/5 functionnumberCount1 (n) {6 varA = []; 7 for(vari = 0; I <= N; i++) {8 A.push (i);9 } Ten vars = A.join (' '); One return(S.length-s.replace (/1/g, "). length); A}
Also has the master to use the bit arithmetic processing, but too advanced, the side dish can not understand ~ ~ ~
In fact, if only consider 400 such a structured integer, there are rules to follow, the side dish gives a calculation of the number of occurrences of the version:
/** * Side dish version * Find out "1" Number of occurrences * can only be judged except the highest bit, the other bits are all 0 integers. For example, 1, 10, 20, 400, 5000. **/functionNumbercount (n) {var_n = parseint (n) | | 0, _z= _n.tostring (). length-1, _w= Math.pow (10, _z), _s= _n/_w, Count = 0; if(_s > 1) {Count= Count +_w; } if(_s = = 1) {Count= Count + 1; } Count= Count + (_W/10) *_s*_z;returncount;}
Through string processing, when the range is smaller, the speed, resource consumption is acceptable, but if the order of magnitude larger, such as 0~400000000, with string processing, obviously inefficient, tested, browser page crashes directly.
And with the algorithm of the side dish, calculate the number of 1 occurrences in the 0~400000000 range, the average time is about 15 milliseconds, but this algorithm can only deal with the highest bit, the other bits are all 0 integers. For example, 1, 10, 20, 400, 5000.
To write this article, not to show off their algorithms, but to thank the community for the active discussion, discussion not only let us Open-minded, but also let us become good at thinking.
Through this small algorithm, let everyone understand: there is no best algorithm, only the most suitable, in different application scenarios, the use of appropriate algorithms, can really improve system efficiency.
How many times has the 0~400 1 appeared?