编写一个方法,数出从0到n中数字2出现了几回?
例如:若是n为20,那么0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 中共2共出现了3次。php
答案1:git
echo substr_count( implode('', range(0, $n)), '2' );
答案2:spa
function countTwo($start, $end){ $c = 0; for($i=$start; $i<=$end; $i++){ $c += substr_count($i, '2'); } return $c; } echo( countTwo(0, 20) );
答案3:code
function countNumber($n, $digit) { $power = 1; //10为底的幂,表明当前计数的位 $count = 0; while($power <= $n) { $r = $n % (10 * $power); //$r 为 $n 不断十进制右移移除的数字组合的数值 $m = ($n-$r)/(10 * $power);//$m 为 $n 不断十进制右移后的值 $currentDigit = intval($r / $power); if($currentDigit < $digit) { $count += $m * $power; } elseif($currentDigit > $digit) { $count += ($m + 1) * $power; } else { $count += ($m + 1) * ($r % $power + 1); } $power *= 10; } return $count; }