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

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

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



function 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];
}

你可能感兴趣的:(php,算法)