Home > Backend Development > PHP Tutorial > node.js - 求php判断几连数的的代码思路。

node.js - 求php判断几连数的的代码思路。

WBOY
Release: 2016-06-06 20:09:57
Original
851 people have browsed it

假如输入一个数222246787
计算出来是4连号
假如输入一个数342222267
计算出来是5连号
.......

求代码思路

回复内容:

假如输入一个数222246787
计算出来是4连号
假如输入一个数342222267
计算出来是5连号
.......

求代码思路

用正则也可以处理,只需要三行代码

<code class="php">function test($num){
  preg_match_all("/(\d)\\1+/",$num,$match);
  rsort($match[0],SORT_NUMERIC);
  return strlen($match[0][0])?:1;
}

echo test("222246787");// 4
echo test(342222267); // 5</code>
Copy after login

把输入的数当作字符串处理,用一个数字记录最大的连数(maxCount),初始值为0,一个记录当前的连数(count)
从下标为1的字符开始,如果当前字符等于它的前一个那么count++,如果不相等count=1
然后maxCount=max(maxCount,count)

1- 设当前号码是 currentNumber = false;
2- 设当前号码连续出现次数是 currentNumberTimes = 1;
3- 设最大连续出现次数是 maxTimes = 0;
4- 设最大连续出现次数对应的数字是 maxTimesNumber = false;
5- 将数字转为字符串,顺序读取每一位,该位的值存入变量 n
6- 将 n 和 currentNumber对比,如果一致 currentNumberTimes ++,否则:
6.1 用currentNumberTimes和maxTimes对比,如果大于maxTimes, maxTimes = currentNumberTimes; maxTimesNumber = currentNumber
6.2 currentNumber = n,currentNumberTimes = 1
7- maxTimesNumber为所求数字, maxTimes为连续出现的次数
注:如果出现相同长度的连续数字,取值为第一个,如 111222,maxTimesNumber = 1, maxTimes = 3

<code>$number = '43124321333334124233343223900';
$currentNumber = false;
$currentNumberTimes = 1;
$maxTimes = 0;
$maxTimesNumber = false;
for ($i = 0, $l = strlen($number); $i  $maxTimes) {
            $maxTimes = $currentNumberTimes;
            $maxTimesNumber = $currentNumber;
        }
        $currentNumberTimes = 1;
        $currentNumber = $n;
    }
}
echo "数字{$maxTimesNumber}连续出现了{$maxTimes}次。\n";
//数字3连续出现了5次。</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template