Codeforces Round 739 (Div. 3) 1560D. Make a Power of Two Solution
Problem Link : https://codeforces.com/problemset/problem/1560/D
Solution in C++:
- /// Author : AH_Tonmoy
- #include <bits/stdc++.h>
- using namespace std;
- using ll = long long ;
- int32_t main() {
- ios_base::sync_with_stdio(0);
- cin.tie(0);
- int t;
- cin >> t;
- while (t--) {
- int n ;
- cin >> n ;
- if ( n & ( n - 1) == 0){
- cout <<"0\n";
- continue ;
- }
- vector<ll>v ;
- for ( int i = 0 ; i <= 60 ; i++){
- v.push_back(1ll<<i);
- }
- string s = to_string(n) ;
- int s_size = s.size() ;
- ll ans = 1e9 ;
- for ( int i = 0 ; i < v.size() ; i++){
- ll s_index = 0 , t_index = 0 , extra = 0 ;
- string t ;
- t = to_string(v[i]);
- int t_size = t.size() ;
- while(s_index < s_size and t_index < t.size()){
- if(s[s_index] == t[t_index]){
- s_index++ , t_index++ ;
- }
- else {
- s_index++,extra++;
- }
- }
- if (s_index == s_size and t_index != t_size){
- extra += (t_size - t_index) ;
- }
- else if (s_index != s_size and t_index == t_size){
- extra += (s_size - s_index) ;
- }
- ans = min(extra,ans) ;
- }
- cout << ans <<'\n';
- }
- return 0 ;
- }
No comments