Sort Integers by The Power Value in C++


As we know that the power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps −

  • if x is even then x = x / 2

  • if x is odd then x = 3 * x + 1

So for example, the power of x = 3 is 7 because 3 uses 7 steps to become 1 (3 → 10 → 5 → 16 → 8 → 4 → 2 → 1). So if we have some integers lo, hi and k. We have to sort all integers in the interval [lo, hi] by the power value in ascending order. Now if two or more integers have the same power value sort them by ascending order. We have to find the k-th integer in the range [lo, hi] sorted by the power value.

For example, if the input is like lo = 12, hi = 15 and k = 2, then output will be 13. This is because the power of 12 is 9, power of 13 is 9, for the 14, this is 17, and for 15 it is also 17, so the sorted sequence is [12,13,14,15] and as k = 2, then the element is 13.

To solve this, we will follow these steps −

  • Define getTurn method, this will take n as input

  • ret := 0

  • while n is not 1

    • if n is odd, then n := n * 3 + 1, otherwise n := n / 2

    • increase ret by 1

  • From the main method

  • for I in range lo to hi

    • make a pair (getTurn(i), i)

    • insert temp into ret

  • sort the pairs based on power, otherwise in ascending order

  • return second value of the pair ret[k - 1]

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   vector < pair <int, int> > ret;
   static bool cmp(pair <int, int>& a, pair <int, int>& b){
      return a.first == b.first ? a.second < b.second : a.first < b.first;
   }
   int getTurn(int n){
      int ret = 0;
      while(n != 1){
         if(n & 1){
            n = n * 3 + 1;
         }
         else n >>= 1;
            ret ++;
      }
      return ret;
   }
   int getKth(int lo, int hi, int k) {
      for(int i = lo; i <= hi; i++){
         pair <int, int> temp;
         temp.first = getTurn(i);
         temp.second = i;
         ret.push_back(temp);
      }
      sort(ret.begin(), ret.end(), cmp);
      return ret[k - 1].second;
   }
};
main(){
   Solution ob;
   cout << (ob.getKth(12, 15, 2));
}

Input

12
15
2

Output

13

Updated on: 29-Apr-2020

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements