第三题C
链接:登录—专业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);
}
}
这题还是比较简单的。