You are given a number N. You can perform the following operations on N any number of times:
> If N is even, divide N by 2.
> If N is odd, replace N with 3N+1.
Your task is to find out, for a given N, if it is possible to reach the number 1 after performing the above two valid operations on N any number of times.
Example:
Input: n = 21
Output: YES
Approach
C++
#include <bits/stdc++.h>using namespace std;string correctIt(long long n){set<long long> st;st.insert(n);int flag = 0;while (n != 1){if (n % 2 == 0){n = n / 2;if (st.find(n) != st.end()){flag = 1;break;}}else{n = n * 3 + 1;if (st.find(n) != st.end()){flag = 1;break;}}}if (flag == 0)return "YES";elsereturn "NO";}int main(){long long n = 21;cout << correctIt(n) << "\n";return 0;}
No comments:
Post a Comment