答案1:
echo substr_count( implode('', range(0, $n)), '2' );
答案2:
function countTwo($start, $end){
$c = 0;
for($i=$start; $i<=$end; $i++){
$c += substr_count($i, '2');
}
return $c;
}
echo( countTwo(0, 20) );
答案3:
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;
}