今天上班发现一个ThoughtWorks的面试题,分享一下
时间:2021-07-01 10:21:17
帮助过:123人阅读
可以接受任意多个特殊数(不包含0),在任意数字范围内输出(1~xxx) 其实还可以用策略模式吧算法独立出来 针对这个题目就先不写了 (偷懒~~)
- class FizzBuzzWhizz{
- private $_special=array();
- private $_words=array();
- public function __construct(array $special,array $words){
- if(in_array(0,$special)){
- exit('特殊数中不能含有0');
- }
- $this->_special=$special;
- $this->_words=$words;
- }
- public function run($num){
- $output='';
- for($i=1;$i<=$num;$i++){
- $output.=$this->_calculate($i);
- }
- echo $output;
- exit();
- }
- private function _calculate($number){
- $str='';
- if(strpos($number,$this->_special[0]) > 0){
- return $this->_words[0]."
"; - }
- foreach($this->_special as $k=>$v){
- if($number%$v === 0){
- $str.=$this->_words[$k];
- }
- }
- return $str==''?$number.'
': $str.' '; - }
- }
- $special=array(3,5,7);
- $words=array('Fizz','Buzz','Whizz');
- $obj=new FizzBuzzWhizz($special,$words);
- $obj->run(100);
|