博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
编写一个方法,数出从0到n中数字2出现了几次?
阅读量:6937 次
发布时间:2019-06-27

本文共 771 字,大约阅读时间需要 2 分钟。

hot3.png

编写一个方法,数出从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次。

答案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;}

转载于:https://my.oschina.net/BearCatYN/blog/406052

你可能感兴趣的文章
Python统计数据的频率
查看>>
如何启动/停止/重启MySQL
查看>>
使用chrome浏览器查看当前网页的http头信息
查看>>
MYSQL对外键的约束要求
查看>>
Linux虚拟机压缩
查看>>
git push 报non-fast-forward updates were rejected 错误
查看>>
Golang安装配置
查看>>
详细地演示gb18030到unicode|utf8的转码过程(RUST语言)
查看>>
KVM 虚拟机在物理主机之间迁移的实现 - IBM
查看>>
Android 4.2 系统编译 找不到添加的内部资源 com.android.internal.R
查看>>
Spring Boot WebFlux + Server-sent事件示例
查看>>
Git for windows 中文乱码解决方案
查看>>
python 爬虫
查看>>
OpenGL超级宝典笔记——雾
查看>>
javaScript元素选择器
查看>>
核心交易链路架构设计与演进
查看>>
websocket-bench压力测试
查看>>
http://91.213.30.151/
查看>>
Android ViewStub详解
查看>>
JavaScript中的prototype、__proto__和constructor
查看>>