c ++ binary answer

c ++ binary answer

problem

So that x ^ x meet or exceed the minimum n-digit positive integers x is the number? n <= 2000000000

analysis

On this issue and difficult to solve, it is difficult to come up with a better solution strategy. But at least we know that the answer must be between 1 and 2 billion, the ability to convert binary thinking to find, binary search of answers it? Of course we can, but there are in binary search in comparison, half of the answer, we need to have more, we use the check function to achieve. If the check out is a legitimate solution, then we try to find a better solution, if it is not legitimate to check out the solution, we try to find a legal solution, which is thought half the answer. In this problem, we design check function is digital x ^ x exceeds n bits, legitimate returns true, illegal returns false. Then we can solve the dichotomy.

AC Code

#include <bits/stdc++.h>
using namespace std;
int o;
bool check(int k)//查看这个数的位数 
{
    long long p = k;
    return p * log10(1.0*k) + 1 >= o;//判断数位的公式 
}
int medium()
{
    int l = 0;//确保范围在 l 和 r 之间  
    int r = 2000000000;
    while (l + 1 < r)//确保不越界(l < r) 
    {
        int mid = (l + r) / 2;
        if (check(mid))//如果这个解满足要求 
        {
            r = mid;//缩小范围 
        }
        else//如果这个解不满足要求 
        {
            l = mid;//继续在右半部分寻找解  
        }
    }
    if (check(l))//如果解合法 
    {
        return l;
    }
    else//不合法 
    {
        return r;
    }
}
int main()
{
    cin >> o;
    cout << medium() << endl;
    return 0;
}

Binary answer ideas summarized:
Step1: in the answer might range [L, R] binary search answers,
Step2: check the current condition of the answer meets the subject requirements
step3: Update lookup segment based on the determination result continues to determine the answer, optimal value
Note:
formula derivation:

Guess you like

Origin www.cnblogs.com/LJA001162/p/11184517.html