1061 Rightmost Digit

Problem Description

Given a positive integer N, you should output the most right 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 rightmost digit of N^N.

Sample Input

1
2
3
2
3
4

Sample Output

1
2
7
6

Suggest Answer

一开始想着是用循环来做,看到题目1<=N<=1,000,000,000的条件,这样子循环的话肯定会超时,数字大一点还有可能会爆int,想到用找规律,可以发现每个数的循环节都是1或者2或者4,可以都把循环节都看成4.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.*;

public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int M = input.nextInt();
for (int i = 0; i < M; i++) {
int N = input.nextInt();
double Mod = N % 10;
List<Integer> ones = new ArrayList<Integer>();
for (int j = 1; j <= 4; j++) {
ones.add((int) Math.pow(Mod, j) % 10);
}
int pos = (N - 1) % 4;
System.out.println(ones.get(pos));
}
input.close();
}
}