Skip to content

Instantly share code, notes, and snippets.

@linkarys
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linkarys/27cfa42e38d82e7fd9b0 to your computer and use it in GitHub Desktop.
Save linkarys/27cfa42e38d82e7fd9b0 to your computer and use it in GitHub Desktop.
<?php
class HurryHenryHooray {
const SEQ_START = 1; // 报数的起始值
const SEQ_END = 100; // 报数的结束値
private $map = []; // 保存数字与字符串的对应关系
public function HurryHenryHooray ($num1, $num2, $num3) {
if ( $this->isValid($num1) && $this->isValid($num2) && $this->isValid($num3) ) {
$this->map[$num1] = 'Hurry';
$this->map[$num2] = 'Henry';
$this->map[$num3] = 'Hooray';
} else {
throw new Exception('非法参数!请输入1 - 9的整数或整数字符串!');
}
}
// 1 - 9 的整数或整数字符串为合法输入值
private function isValid ($num) {
return ( ctype_digit($num) || is_int($num) ) && $num < 10 && $num > 0;
}
// 打印一行数据
private function printLine ($str) {
echo $str . PHP_EOL;
}
// 报数
public function countOff () {
for ($i = self::SEQ_START; $i <= self::SEQ_END; $i++) {
// 获取第一个特殊数
reset($this->map);
$first_key = key($this->map);
// 假如所报数字包含了第一个特殊数,输出第一个特殊数对应的单词,
// 并且忽略其它规则
if ( strpos( (string)$i, (string)$first_key ) > -1 ) {
$this->printLine($this->map[$first_key]);
} else {
$str = "";
// 处理倍数关系
foreach ($this->map as $key => $value) {
if ($i % $key === 0) {
$str .= $this->map[$key];
}
}
$this->printLine($str ? $str : $i);
}
}
}
}
// 测试
$hhh = new HurryHenryHooray(3, 5, 7) //输入整数或整数字符串
echo '<pre>';
$hhh->countOff();
echo '</pre>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment