編寫一個方法,數出從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; }