35437

[剑指offer]数值的整数次方

<h2 class="subject-item-title">题目描述</h2> 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。   保证base和exponent不同时为0     题目链接: https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking package com.sunshine.OFFER66_SECOND; import org.junit.Test; public class A12_Power { @Test public void test() { System.out.println(Power(0, 2)); System.out.println(Power2(0,2)); } public double Power(double base, int exponent) { return Math.pow(base, exponent); } public double Power2(double base, int exponent) { double ans = base; boolean flag = false; if (exponent < 0) { flag = true; exponent = -exponent; } if(base == 0 ){ return 0; }else if ( exponent == 0) { return 1; } else if (exponent == 1) { return ans; } else if (exponent >= 2) { exponent--; } while (exponent > 0) { ans *= base; exponent--; } if (flag) { ans = 1 / ans; } return ans; } }

来源:博客园

作者:MoonBeautiful

链接:https://www.cnblogs.com/MoonBeautiful/p/11425620.html

Recommend