# HDOJ--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
2
3
4

Sample Output
7
6

Hint
In the first case, 3 * 3 * 3 = 27, so the rightmost digit is 7.
In the second case, 4 * 4 * 4 * 4 = 256, so the rightmost digit is 6.

#include <iostream>
#include <string>
using namespace std;

int getRightDigit(string n)
{
return n[n.length() - 1] - '0';
}

int main()
{
int t;
cin >> t;
for (int i = 0; i < t; ++i)
{
string n;
cin >> n;

int result = 1;
int len = atoi(n.c_str());
string tmp = n;
for (int j = 1; j < len; ++j)
{
result = getRightDigit(tmp)*getRightDigit(n);
char buf[100];
sprintf(buf, "%d", result);
tmp = buf;
result = getRightDigit(tmp);
}
cout << result << endl;
}
return 0;
}

4 ^ 999
= 4 ^ (512 + 256 + 128 + 64 + 32 + 4 + 2 + 1)
= (4 ^ 512) * (4^ 256) * (4 ^ 128) * (4 ^ 64) * (4 ^ 32) * (4 ^ 4) * (4 ^ 2) * 4

REVERSE_BINARY(n)
1 while (n > 0)
2 do output (n mod 2)
3 n ← n / 2

POWER_INTEGER(x, n)
1 pow ← 1
2 while (n > 0)
3 do if (n mod 2 = 1)
4 then pow ← pow * x
5 x ← x * x
6 n ← n / 2
7 return pow

#include <iostream>
#include <string>
using namespace std;

int main()
{
int t;
cin >> t;
for (int i = 0; i < t; ++i)
{
int n;
cin >> n;
int tmp = n % 10;       //防止溢出,即n的个位
int result = 1;
while (n)
{
if (n&1)            //若n为奇数
{
result *= tmp;
result %= 10;
}
tmp *= tmp;
tmp %= 10;
n /= 2;
}
cout << result << endl;

}

return 0;
}


• 本文已收录于以下专栏：

举报原因： 您举报文章：HDOJ--Rightmost Digit 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)