duanfu7840 2011-02-01 15:55
浏览 23
已采纳

算法错误

I have a script:

function convert($src, $srcAlphabet = '0123456789', $dstAlphabet =
    'qwertyuiopasdfghjklzxcvbnm')
{
    $srcBase = strlen($srcAlphabet);
    $dstBase = strlen($dstAlphabet);

    $wet = $src;
    $val = 0;
    $mlt = 1;

    while($l = strlen($wet))
    {
        $digit = $wet[$l - 1];
        $val += $mlt * strpos($srcAlphabet, $digit);
        $wet = substr($wet, 0, $l - 1);
        $mlt *= $srcBase;
    }

    $wet = $val;
    $dst = '';

    while($wet >= $dstBase)
    {
        $digitVal = $wet % $dstBase;
        $digit = $dstAlphabet[$digitVal];
        $dst = $digit . $dst;
        $wet /= $dstBase;
    }

    $digit = $dstAlphabet[$wet];
    $dst = $digit . $dst;

    return $dst;
}

for($i = 0; $i < 10000; $i++)
{
    echo $i . ' = ' . convert(substr(' ' . $i, 1)) . '<br>';
}

It works fine, however the result is strange... it looks like that:

0 = q
1 = w
2 = e
3 = r
4 = t
5 = y
6 = u
7 = i
8 = o
9 = p
10 = a
11 = s
12 = d
13 = f
14 = g
15 = h
16 = j
17 = k
18 = l
19 = z
20 = x
21 = c
22 = v
23 = b
24 = n
25 = m
26 = wq
...
...
676 = wqq
677 = wqw
678 = wqe
...

but 26 should be qq, 676 should be qqq, 677 = qwq, 678 = qqe etc.

why it's starting from w instead of q (except for 0)?

  • 写回答

4条回答 默认 最新

  • duanchuo7741 2011-02-01 16:20
    关注

    If you change

    $wet /= $dstBase;
    

    to

    $wet = $wet / $dstBase - 1;
    

    your code will give the correct result. However, as Soren noted, using PHP functionality you can accomplish things much easier.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分