HDU - 1061-快速幂签到题

快速幂百度百科:快速幂就是快速算底数的n次幂。其时间复杂度为 O(log₂N), 与朴素的O(N)相比效率有了极大的提高。

HDU - 1061

代码实现如下:

import java.util.Scanner;

public class Main
{
    public static void main(String []args)
    {
        Scanner cin = new Scanner(System.in);
        int T = cin.nextInt();
        for(int i = 0; i < T; i++)
        {
            int N = cin.nextInt();
            System.out.println(Search(N));
        }
    }
    static int Search(int N)//快速幂的模板一般都与下面的代码相同
    {
        int ans = 1;
        int temp = N;
        while(N != 0)
        {
            if((N & 1) != 0)
            {
                ans = (ans%10)*(temp%10);
            }
            temp = (temp%10) * (temp%10);
            N = N>>1;
        }
        ans = ans%10;
        return ans;
    }
}

 

posted @ 2018-11-24 19:46  给我一个团队,干翻TX  阅读(140)  评论(0编辑  收藏  举报