Sort by

recency

|

2012 Discussions

|

  • + 0 comments

    Perl:

    sub utopianTree {
        my $n = shift;
        
        return ($n % 2 == 0) ? (2 ** (($n / 2) + 1)) - 1 : (2 ** ((($n + 1) / 2) + 1)) - 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
    int height = 0;
        int i = 0;
        while(i<=n) {
            height = i % 2 ==0 ? height + 1 : height * 2;
            i++;
        }
        return height;
    
  • + 0 comments
    if(n%2==0)
        height = pow(2,(n/2) +1) -1 ;
    else
        height = pow(2,((n+1)/2) +1) -2 ;
    
  • + 0 comments

    C#

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