zoukankan      html  css  js  c++  java
  • Designing Efficient Algorithms [Examples]~C

    Alice got a hold of an old calculator that can display n digits. She was bored enough to come up with the following time waster.

    She enters a number k then repeatedly squares it until the result overflows. When the result overflows, only the n most significant digits are displayed on the screen and an error flag appears. Alice can clear the error and continue squaring the displayed number. She got bored by this soon enough, but wondered:

    “Given n and k, what is the largest number I can get by wasting time in this manner?”

    Input

    The first line of the input contains an integer t (1 ≤ t ≤ 200), the number of test cases. Each test case contains two integers n (1 ≤ n ≤ 9) and k (0 ≤ k < 10n) where n is the number of digits this calculator can display k is the starting number.

    Output

    For each test case, print the maximum number that Alice can get by repeatedly squaring the starting number as described.

    Sample Input

    2

    1 6

    2 99

    Sample Output

    9

    99

    解题思路:题目意思是:有一个老式计算机,只能显示n位数字。有一天,你无聊了,于是输入一个整数k,然后反复平方,直到溢出。每次溢出时,计算机会显示出结果的最高n位和一个错误标记。然后清除标记,继续平方。如果一直这样做下去,能得到的最大数是多少?比如,当n=1,k=6时,计算机将依次显示6、3(36的最高位),9、8(81的最高位),6(64的最高位),3,..........

    程序代码:

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <cmath>
    #include <set>
    using namespace std;
    
    int next(int n, int k)
    {
        long long res = (long long)k*k;
    
        while(res >= n)
            res/=10;
        return res;
    }
    
    int main()
    {
        int T;
        scanf("%d", &T);
        for(int i=0;i<(T);i++)
        {
            int n, k;
            scanf("%d%d", &n, &k);
            n = (int)pow(10.0, n);//计算10的n次幂赋值给n
            int ans = 1<<31;
            set<int> ss;
            while(1)
            {
                ans = max(ans, k);
    
                if(ss.count(k))
                    break;
                else
                    ss.insert(k);//把k放入容器
    
                k = next(n, k);
            }
    
            printf("%d
    ", ans);
        }
        return 0;
    }
    

     

  • 相关阅读:
    document.body.appendChild 的问题
    页面不刷新,表单提交到弹出窗口或Iframe
    您对无法重新创建的表进行了更改或者启用了 阻止保存要求创建表的更改
    转载:兼容各类浏览器的CSS Hack技巧
    sql server 代理权限问题
    配置SQL用户访问指定表,指定列
    关于嵌入式系统的启动(装载)
    centos 中安装g++
    嵌入式中利用ftp实现宿主机与目标机通信
    TQ2440加载Hello world驱动模块
  • 原文地址:https://www.cnblogs.com/chenchunhui/p/4925056.html
Copyright © 2011-2022 走看看