Sort by

recency

|

2001 Discussions

|

  • + 0 comments

    // the function code will be simply............. public static int utopianTree(int n) { int height=1; for(int i=0;i

        }
        else{
            height=height+1;
        }
    }
    return height;
    
    }
    

    }

  • + 0 comments

    solution 1: O(1) cpp solution--

    int utopianTree(int n) { int exponent=n/2 +1 +n%2; int result=pow(2,exponent); if(n%2==0){ return result-1; } else{ return result-2; } }

  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/0G-kEeQC25E

    Solution 1 : O(N)

    int utopianTree(int n) {
        int ans = 1;
        for(int i = 1; i <= n; i++){
            if(i % 2 == 0) ans++;
            else ans *=2;
        }
        return ans;
    }
    

    Solutoin 2 : O(1)

    int utopianTree(int n) {
        string s(n / 2 + 1, '1');
        if(n % 2 == 1) s += '0';
        bitset<60> ans(s); 
        return ans.to_ullong();
    }
    

    Solutoin 3 : O(1)

    int utopianTree(int n) {
        int ans = (1 << ((n / 2) + 1) ) - 1;
        if(n % 2 == 1) ans*=2;
        return ans;
    }
    

    Solutoin 4 : O(1)

    int utopianTree(int n) {
        return ((1 << ((n / 2) + 1) ) - 1) << n%2;
    }
    
  • + 0 comments
    function utopianTree(n) {
        
        var height = 1
        var double_hight_growth = true
        
        for (var i = 1; i <=n ;i++){
            
            if (double_hight_growth){
                
                double_hight_growth = false
                height =  2 * height
                
            }
            else{
                
                double_hight_growth = true
                height = height + 1
            }
            
            
        }
        return height
    
    }
    
  • + 0 comments

    Php solution;

    function utopianTree($n) {
        // Write your code here
        $height = 1;
        for($i = 1; $i <= $n; $i++) {
            // is summer
            if ($i % 2 == 0) {
                $height += 1;
            } else {
                // is spring
                $height *= 2; 
            }
        }
        return $height;
    }