整数中1出现的次数(从1到n整数中1出现的次数)

来源:互联网 发布:固定收益 知乎 编辑:程序博客网 时间:2024/06/18 00:31

1~13中包含1的数字有1、10、11、12、13,1共出现6次。求任意非负整数区间中1出现的次数。

链接:https://www.nowcoder.com/questionTerminal/bd7f978302044eee894445e244c7eee6?toCommentId=567854
来源:牛客网

<?phpfunction NumberOf1Between1AndN_Solution($n){    if ($n==0){        return 0;    }    if ($n==1){        return 1;    }    //1至n之间的数组成数组,拼接成字符串    $str=implode(range(1,$n));    字符串分割为数组    $arr=str_split($str);    计算数组中1的个数    return array_count_values($arr)[1];}
原创粉丝点击