1~13中包含1的数字有1、10、11、12、13,1共出现6次。求任意非负整数区间中1出现的次数。
链接:https://www.nowcoder.com/questionTerminal/bd7f978302044eee894445e244c7eee6?toCommentId=567854 来源:牛客网
<?php
function NumberOf1Between1AndN_Solution($n)
{
if (
$n==
0){
return 0;
}
if (
$n==
1){
return 1;
}
$str=implode(range(
1,
$n));
字符串分割为数组
$arr=str_split(
$str);
计算数组中
1的个数
return array_count_values(
$arr)[
1];
}