c++ simple recursive version.


  • 0
    class Solution {
    public:
      int integerReplacement(int n) {
        return recursive(n, 0);
      }
      int recursive(int n, int steps)
      {
        if (n == 1)
        {
          return steps;
        }
        if (n % 2 == 0)
        {
          return recursive(n / 2, steps + 1);
        }
        else
        {
          return min(recursive(n + 1, steps + 1), recursive(n - 1, steps + 1));
        }
      }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.