快速幂的求解-java方法(int范围之内)

思想就是,将十进制数化成二进制数。其它就是很简单了。

如:2的11次幂,11的二进制位1011,所以2(11) = 2(2(0) + 2(1) + 2(3));

具体实现步骤,看代码比较简单

import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner cin = new Scanner(System.in);
        //底数
        int a = cin.nextInt();
        //指数
        int b = cin.nextInt();
        int sum = 1;
        int temp = a;
        while(b != 0)
        {
            //取其末位
            if((b & 1) != 0)
            {
                sum = sum * temp;
            }
            temp = temp * temp;
            //除其末位
            b = b>>1;
        }
        System.out.print(sum);
    }
}

猜你喜欢

转载自www.cnblogs.com/674001396long/p/9759606.html