【HDU 1060】Leftmost Digit

Leftmost Digit

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3132 Accepted Submission(s): 1375
 
Problem Description
Given a positive integer N, you should output the leftmost digit of N^N.
 
Input
The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single positive integer N(1<=N<=1,000,000,000).
 
Output
For each test case, you should output the leftmost digit of N^N.
 
Sample Input
2
3
4
 
Sample Output
2
2
Hint
In the first case, 3 * 3 * 3 = 27, so the leftmost digit is 2.
In the second case, 4 * 4 * 4 * 4 = 256, so the leftmost digit is 2.



此题可以说是一道数学问题。

不妨假设当输入n时,首位是x,n的n次方的位数是l,很显然,x==(n的n次方)/(10的l-1次方)。

将上式两端同时取以10为低的对数得到lg(x)==lg(n的n次方)-(l-1),

化简得到x==pow(10,n*lg(n)-(l-1)),现在我们只需要知道n*lg(n)-(l-1)这个代表什么即可。

lg(n的n次方)可以看成是“10的?次方==n的n次方”,显然,lg(n的n次方)的整数部分就是n的n次方的位数-1,即l-1。

所以就能解出x。

代码如下:




#include <cstdio>
#include <cmath>
int main()
{
    double n,x;
    int t;
    scanf("%d",&t);
    while(t--)
    {
            scanf("%lf",&n);
            x=n*log10(n)-(long long)(n*log10(n));
            printf("%d
",(int)pow(10.0,x));
    }
}



原文地址:https://www.cnblogs.com/Torrance/p/5410569.html