描述
求N^N的个位数字大家应该都会了,可是,N^N的最高位
字你会求吗?
输入
多组测试数据。
每组数据输入一个正整数N(N≤1,000,000,000)。
输出
对于每组数据,输出N^N的最高位数字。
样例输入
3
4
样例输出
2
2
一开始看到题就想到了BigInteger,所以写了
public class Main {
static Scanner scan=new Scanner(System.in);
public static void main(String[] args){
Main test8=new Main();
while(scan.hasNext()){
test8.start();
}
}
public void start(){
int a=scan.nextInt();
BigInteger bigInteger=new BigInteger(""+a);
BigInteger bigInteger2=new BigInteger(""+a);
for(int i=1;i<a;i++){
bigInteger=bigInteger.multiply(bigInteger2);
}
String s=bigInteger.toString();
System.out.println(s.charAt(0));
}
}
但是超时。。。
网上观摩大神想法:
http://www.jeepshoe.org/2015/1419560.html
http://www.fx114.net/qa-146-114921.aspx
于是写下如下代码。
主要是关于对数的应用,可以先去看一下对数的性质。首先第一步。N^N以十为第的对数是多少?设为b。所以10^b就是N^N.
第二步:通过对数性质N^N以10为底的对数可以写成N*(log(10)N)=b.
第三步:b肯定是一个分数 b=x(整数)+y(分数)而10^(x+y)=(10^x)*(10^y)
第四步:因为10^x第一位肯定是1。10^y的范围肯定是大于1小于9。因为以10为底,1的对数为0,y>0;所以最后只要取10^y的整数部分就可以。
import java.util.Scanner;
public class Main {
static Scanner scan=new Scanner(System.in);
public static void main(String[] args){
Main test8=new Main();
while(scan.hasNext()){
test8.start();
}
}
public void start(){
int a=scan.nextInt();
double x=(double)a*Math.log10(a);
double y=(double)x-(long)x;
System.out.println((int)Math.pow(10.0, y));
}
}