数据结构3:时间复杂度计算举例

题目:x的n次方,结果输出

package demo4_8;

public class leijia {
    static int temp;
    public static void main(String[] args) {
        //一道题目思考递归的时间复杂度
        //问题:x的n次方
        int x=2;
        int n=8;
        System.out.println("方法一:"+method1(x,n));
        System.out.println("方法二:"+method2(x,n));
        System.out.println("方法三:"+method3(x,n));
        System.out.println("方法四:"+method4(x,n));
    }

    //方法一:直接求解(时间复杂度为O(n)
    public static int method1(int x,int n){
        int result=1;
        for(int i=0;i<n;i++){
            result*=x;
        }
        return result;
    }

    //方法二:递归的方法:时间复杂度还是O(n)
    public static int method2(int x,int n){
        if(n==0) return 1;
        return method2(x,n-1)*x;
    }
    //方法三:递归的方法:时间复杂度还是O(n)
    //通过满二叉树进行计算,时间复杂度还是O(n)
    public static int method3(int x,int n){
        if(n==0) return 1;
        if(n%2==1) return method3(x,n/2)*method3(x,n/2)*x;
        return method3(x,n/2)*method3(x,n/2);
    }

    //方法四:递归的方法:时间复杂度还是O(n)
    public static int method4(int x,int n){
        if(n==0) return 1;
        temp=method4(x,n/2); //记录中间变量
        System.out.println("次数");
        if(n%2==1) return temp*temp*x;
        return temp*temp;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值