How to increase php string by 1: 1. Create a new php sample file; 2. Create the "function inc($s) {...}" method; 3. Pass "while ($n-- > 0) {$s = inc($s);}" Calculate the string except the last character, and then carry.
The operating environment of this tutorial: Windows 10 system, PHP version 8.1, DELL G3 computer
How to increase the php string by 1 ?
php Numeric string 1 operation accumulates and adds one (no overflow)
* 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\n", $s); $s = inc($s); } printf("%s\n", $s); // "2147493647"
Recursion, if carry is needed , first calculate the string excluding the last character, and set the last character to '0'; single numeric characters 0-9 are obviously easy to handle.
* test:
<?php $m = 2147483647; $n = 10000; while ($n-- > 0) { // printf("%d\n", $m); $m++; } printf("%d\n", $m);
The comparison results are consistent
* add2.php // Traverse 1-4 uppercase letters
<?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\n", $s); } while ($s != "ZZZZ");
Recommended learning: "PHP video tutorial"
The above is the detailed content of How to increase php string by 1. For more information, please follow other related articles on the PHP Chinese website!