php字符串增加1如何实现

后端开发   发布日期:2023年06月11日   浏览次数:231

这篇“php字符串增加1如何实现”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“php字符串增加1如何实现”文章吧。

php字符串增加1的实现方法:1、新建php示例文件;2、创建“function inc($s) {...}”方法;3、通过“while ($n-- > 0) {$s = inc($s);}”计算除去最后一个字符的字符串,然后进位即可。

php 数字字符串 +1 操作 累加 加一 (不溢出)

* inc.php

<?php
 
function inc($s) {
    if (empty($s)) {return "1";}
    if ( ! isset($s[1]) ) {
        $code = ord($s[0]) + 1;
        if ($code <= ord("9")) {
            return chr($code);
        }
        return "10";
    }
    $n = strlen($s);
    $code = ord($s[$n-1]) +1;
    if ($code <= ord("9")) {
        return substr($s, 0, $n-1).chr($code);
    }
    return inc(substr($s, 0, $n-1))."0";
}
 
$s = "2147483647";
$n = 10000;
while ($n-- > 0) {
    // printf("%s
", $s);
    $s = inc($s);
}
printf("%s
", $s); // "2147493647"

递归,如果需要进位, 先计算除去最后一个字符的字符串, 最后一个字符置为'0'; 单个数字字符0-9显然好处理。

* test:

<?php
 
$m = 2147483647;
 
$n = 10000;
while ($n-- > 0) {
    // printf("%d
", $m);
    $m++;
}
printf("%d
", $m);

比较结果一致

* add2.php // 遍历1-4位大写字母

<?php
 
function add($s) {
    if (empty($s)) {return "A";}
    if ( ! isset($s[1]) ) {
        $code = ord($s[0]) + 1;
        if ($code <= ord("Z")) {
            return chr($code);
        }
        return "AA";
    }
    $n = strlen($s);
    $code = ord($s[$n-1]) +1;
    if ($code <= ord("Z")) {
        return substr($s, 0, $n-1).chr($code);
    }
    return add(substr($s, 0, $n-1))."A";
}
 
$s = "";
do {
    $s = add($s);
    printf("%s
", $s);
} while ($s != "ZZZZ");

以上就是php字符串增加1如何实现的详细内容,更多关于php字符串增加1如何实现的资料请关注九品源码其它相关文章!