HD1060Leftmost Digit

 

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11011 Accepted Submission(s): 4214

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.

一开始用java做,果断超时,不过用java给我的感觉是,几天没用,就感觉有点陌生了,把这个代码记录下来,还是挺不错的:

import java.math.BigInteger;
import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
        int i;
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        for(i=0;i<n;i++){
            BigInteger b =cin.nextBigInteger();
            int c = b.intValue();
            b = b.pow(c);
            String e = b.toString();
            System.out.println(e.charAt(0));            
        }
    }
}

题解思路,利用公式n=10^x*m=>lgn=x+lg(m);

具体步骤:
1.对M=N^N两边取对数得log10(M)=N*log10(N),即M=10^(N*log10(N))
2.要求M的最高位,则令N*log10(N)=a+b;b是小数(0<=b<1),a是整数。
3.因为10的任何整数次幂首位一定为1,所以,M的首位只和N*log10(N)的小数部分有关,

#include<iostream>
using namespace std;
int main(){
    int n,i,result;
    long long s;
    cin>>n;
    while(n--){
        cin>>s;
        double x1 = s*log10( 1.0*s);
        double x2 = x1 - (long long)x1;
        result = 0;
        result = (int)pow(10.0,x2);
        cout<<result<<endl;
    }
    return 0;
}

所以只用求10^b就可以了。(1<=10^b<10)
4.求出b也很简单,只要用double类型的(N*log10(N))去减去long long类型的(N*log10(N))。

原文地址:https://www.cnblogs.com/LZYY/p/3292828.html