Sort by

recency

|

2014 Discussions

|

  • + 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
    def utopianTree(n):
        # Write your code here
        return 2 ** (math.floor((n + 1) / 2) + 1) - 1 - (n % 2)
    
  • + 0 comments

    My C++ solution -

    int utopianTree(int n) {
        int height = 1;
        auto is_odd = [](int num){ return (num & 1);};
        
        for (int i=1;i<=n;i++) {
            if (is_odd(i)) {
                height *= 2;
            } else {
                height += 1;
            }
        }
        
        return height;
    }
    
  • + 0 comments

    Perl:

    sub utopianTree {
        my $n = shift;
        
        return ($n % 2 == 0) ? (2 ** (($n / 2) + 1)) - 1 : (2 ** ((($n + 1) / 2) + 1)) - 2;
    }
    
  • + 1 comment
    int height = 0;
        int i = 0;
        while(i<=n) {
            height = i % 2 ==0 ? height + 1 : height * 2;
            i++;
        }
        return height;
    
    • + 0 comments

      def one_cycle(height_one): return (2*height_one +1)

      def utopianTree(n): # Write your code here height=1

          cycles=n//2    
      
      if cycles:
          for i in range (cycles):
              height=one_cycle(height) 
      if n%2==0:
          return height
      else: 
      
          return (2*height)