Reverse string without strrev

前端 未结 23 1007
忘了有多久
忘了有多久 2020-12-13 13:19

Some time ago during a job interview I got the task to reverse a string in PHP without using strrev.

My first solution was something like this:

23条回答
  •  一向
    一向 (楼主)
    2020-12-13 14:05

    You could use the XOR swap trick.

    function rev($str) {
        $len = strlen($str);
    
        for($i = 0; $i < floor($len / 2); ++$i) {
            $str[$i] = $str[$i] ^ $str[$len - $i - 1];
            $str[$len - $i - 1] = $str[$i] ^ $str[$len - $i - 1];
            $str[$i] = $str[$i] ^ $str[$len - $i - 1];
        }
    
        return $str;
    }
    
    print rev("example");
    

提交回复
热议问题