美文网首页
力扣476(数字的补数)

力扣476(数字的补数)

作者: designer | 来源:发表于2021-10-18 16:31 被阅读0次

    力扣数字的补数链接

    题解:

    class Solution {
    
        /**
         * @param Integer $num
         * @return Integer
         */
        function findComplement($num) {
            if($num==1){
                return 0;
            }
            $binNum = $this->toBin($num);
            $rev = $this->toRev($binNum);
            $result = 0;
            $len = strlen($rev);
            for($j = $len -1 ; $j>=0;$j-- ){
                if(substr($rev,$j,1)==1){
                    $result+= pow(2,$len-$j-1);
                }
            }
            return $result;
        }
    
        private function toBin($nums){
            if($nums==0 || $nums == 1){
                return $nums;
            }
            $divisor = intval($nums/2);
            $binNum = intval($nums%2);
            return $binNum.$this->toBin($divisor);
        }
    
        private function toRev($binNum){
            $rev='';
            $binNum = strrev($binNum);
            for($i = 0 ; $i<strlen($binNum);$i++){
                if(substr($binNum,$i,1)==1){
                    $rev.='0';
                }else{
                    $rev.='1';
                }
            }
            return $rev;
        }
    }
    

    相关文章

      网友评论

          本文标题:力扣476(数字的补数)

          本文链接:https://www.haomeiwen.com/subject/zeenoltx.html