求ascii 然后做运算

介绍
ABC 返回每个字符的ascii A->65 B->66 C->77
组成656667
把所有的7替换成1
然后变成 656667 和 656661
每个数值做加法 然后做减法
(6 + 5 + 6 + 6 + 6 + 7) - (6 + 5 + 6 + 6 + 6 + 1)
------------------------- 6
 
自己写的:
function calc($s) {
    // Your code here
    $num = '';
    for($i=0;$i<strlen($s);$i++)
    {
        $str = substr($s,$i,1);
        $num .= ord($str);
    }
    $old_num = $num;
    $new_num = str_replace("7","1",$num);
 
    $old_sum = 0;
    $new_sum = 0;
    for($t=0;$t<strlen($old_num);$t++)
    {
        $sum_old = substr($old_num,$t,1);
        $old_sum = $old_sum + intval($sum_old);
        $sum_new = substr($new_num,$t,1);
        $new_sum = $new_sum + intval($sum_new);
    }
 
    return $old_sum-$new_sum;
}
 
大神写的:
function calc($s) {
    return substr_count(implode(array_map('ord', str_split($s))), '7') * 6;
}
posted @ 2018-09-09 08:49  IT.狂人  阅读(357)  评论(0编辑  收藏  举报