[PHP] 算法-数值的整数次方的PHP实现
2024-08-25 13:45:43
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。 思路:
1.指数的二进制表达10^6次方 可以表示10^110(二进制) 10^100 * 10^10 * 10^000=>10^4 * 10^2
2.移位运算 while(n!=0){
if((n&1)==1)
res*=curr;
curr*=curr;// 翻倍
n>>=1;// 右移一位
}
<?php
function Power($base, $n){
$res = 1;
$curr = $base;
$exponent;
if($n>0){
$exponent = $n;
}else if($n<0){
if($base==0) return 0;
$exponent = -$n;
}else{// n==0
return 1;// 0的0次方
}
//$exponent转成二进制,有多少位就循环多少次,curr就执行n+1次方,如果当前位是1的就结果相乘
while($exponent!=0){
if(($exponent&1)==1)
$res*=$curr;
$curr*=$curr;// 翻倍
//var_dump($curr);
$exponent>>=1;// 右移一位
}
return $n>=0?$res:(1/$res);//指数是负数的情况
} $a=Power(10,6);
var_dump($a);
~
最新文章
- 瘋子C++笔记
- C#学习手册
- 消息队列MQ - Apache ActiveMQ
- CentOS - 开机自动发送IP到指定邮箱 - smtp.163.com
- php基础08:改变数据类型
- git冲突的发生和解决/git workspace关于git的配置
- Windows任务计划
- BZOJ 4636 蒟蒻的数列
- 【Android - 进阶】之自定义视图浅析
- 第 6 章 抽象工厂模式【Abstract Factory Pattern】
- Kaggle Bike Sharing Demand Prediction – How I got in top 5 percentile of participants?
- Node.js - 阿里Egg的多进程模型和进程间通讯
- pyqt pyside QLabel 显示图片
- BZOJ1503[NOI2004]郁闷的出纳员——treap
- Django(四)框架之第三篇模板语法
- post请求中data参数的应用
- JavaScript学习历程03
- HBase 笔记1
- 安装xampp出错,windows找不到-n ?
- Linux 子网掩码计算, 二进制十进制互相转换