[USACO 2010 Nov B]Math 投机取巧Java代码

第三题C

Math Practice

链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld

题目描述

One lovely afternoon, Bessie's friend Heidi was helping Bessie review for her upcoming math exam.
Heidi presents two integers A (0 <= A <= 45) and B (1 <= B <= 9) to Bessie who must respond with an integer E in the range 1..62. E is the smallest integer in that range that is strictly greater than A and also has B as the first digit of 2 raised to the E-th power. If there is no answer, Bessie responds with 0.
Help Bessie correctly answer all of Heidi's questions by calculating her responses.

By way of example, consider A=1 and B=6. Bessie might generate a table like this:
         E         2^E    First digit of 2^E
         2          4            4
         3          8            8
         4         16            1
         5         32            3
         6         64            6      <-- matches B
Thus, E=6 is the proper answer.

NOTE: The value of 2^44 does not fit in a normal 32-bit integer.

译本:一个可爱的下午,贝西的朋友海蒂正在帮贝西复习即将到来的数学考试。

Heidi向Bessie呈现两个整数A (0 <= A <= 45)和B (1 <= B <= 9), Bessie必须以1..62范围内的整数E作为回应。E是这个范围内严格大于A的最小的整数,并且B是2的E次幂的第一个数字。如果没有人回答,贝西就回答0。

通过计算海蒂的回答,帮助贝西正确回答海蒂的所有问题。

举例来说,假设A=1, B=6。贝西可能生成这样一个表:

2^E的第一个数字

2 4 4

3 8 8

4 16 1

5 32 3

6 64 6 <——匹配B

因此,E=6是正确答案。

注意:2^44的值不适合正常的32位整数。

输入描述:

* Line 1: Two space-separated integers: A and B
(输入 A B)

输出描述:

* Line 1: A single integer E calculated as above
(如上所述计算的单个整数E)

示例1

输入

  

1 6 

输出

    

6

注意:

当A大时选取不当的数据类型会越界。

当E>62时,输出0。

思路:

1.数学

可以用不断取模的方法得到第一位,这里就不写了噢。

2.投机取巧

用BigInteger存数字,肯定不会越界,并且我们可以将它toString 后可以用subString得到首位!

代码

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b= scanner.nextInt();
        int e = a + 1;
        BigInteger bi = BigInteger.valueOf(2);
        bi = bi.pow(e);
        while (Integer.parseInt(bi.toString().substring(0, 1)) != b) {
            bi = BigInteger.valueOf(2);
            e++;
            bi = bi.pow(e);
        }
        if (e > 62) {
            e = 0;
        }
        System.out.println(e);
    }
}

这题还是比较简单的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

L_59

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值