Home >Backend Development >PHP Tutorial >I found a ThoughtWorks interview question at work today. Let me share it.

I found a ThoughtWorks interview question at work today. Let me share it.

WBOY
WBOYOriginal
2016-07-25 08:48:141447browse
It can accept any number of special numbers (excluding 0) and output (1~xxx) in any number range. In fact, you can also use the strategy mode to make the algorithm independent. I won’t write about this topic yet (lazy~~)
    class FizzBuzzWhizz{
  1. private $_special=array();
  2. private $_words=array();
  3. public function __construct(array $special,array $words){
  4. if(in_array(0 ,$special)){
  5. exit('Special numbers cannot contain 0');
  6. }
  7. $this->_special=$special;
  8. $this->_words=$words;
  9. }
  10. public function run( $num){
  11. $output='';
  12. for($i=1;$i<=$num;$i++){
  13. $output.=$this->_calculate($i);
  14. }
  15. echo $output;
  16. exit();
  17. }
  18. private function _calculate($number){
  19. $str='';
  20. if(strpos($number,$this->_special[0]) > 0){
  21. return $this->_words[0]."
    ";
  22. }
  23. foreach($this->_special as $k=>$v){
  24. if($number%$v === 0){
  25. $str.=$this->_words[$k];
  26. }
  27. }
  28. return $str==''?$number.'
    ': $str.'
    ';
  29. }
  30. }
  31. $special=array(3,5,7);
  32. $words=array('Fizz','Buzz','Whizz');
  33. $obj=new FizzBuzzWhizz($special,$ words);
  34. $obj->run(100);
Copy code

Statement:
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