首页 > 其他分享 >3616、n的幂

3616、n的幂

时间:2023-02-14 14:37:30浏览次数:37  
标签:assertTrue 3616 pow Assert mp assertEquals powerOfN

package cn.fansunion.leecode.math;

/**

* @author [email protected]

*

* 2022-2-23

*/

public class MathPower {

/**

* 判定一个数n是否为某个数a的b次方。PowerOfThree,PowerOfFour,本质都是PowerOfN。

*

* @param num

* @param n

*/

public boolean powerOfN(int n, int a) {

if (n <= 0) {

return false;

}

if (n == 1) {

return true;

}

// >=a

while (n >= a) {

if (n % a == 0) {

n = n / a;

} else {

return false;

}

}

// 1

return n == 1;

}

/**

* Math.pow(a,b),支持整数,b>=0;2的3次方=8

*

* @param a

* @param b

* @return

*/

public int pow(int a, int b) {

if (b < 0) {

throw new IllegalArgumentException("b<0");

}

if (b == 0) {

return 1;

}

int n = 1;

for (int index = 0; index < b; index++) {

n = n * a;

}

return n;

}

}
package test.leecode.math;

import org.junit.Assert;

import org.junit.Test;

import cn.fansunion.leecode.math.MathPower;

/**

* @author [email protected]

*

* 2022-2-23

*/

public class MathPowerTest {

@Test

public void test() {

MathPower mp = new MathPower();

// 4

Assert.assertTrue(mp.powerOfN(16, 4));

Assert.assertTrue(mp.powerOfN(256, 4));

Assert.assertTrue(mp.powerOfN(4, 4));

Assert.assertTrue(mp.powerOfN(1, 4));

Assert.assertFalse(mp.powerOfN(-1, 4));

Assert.assertFalse(mp.powerOfN(3, 4));

Assert.assertFalse(mp.powerOfN(257, 4));

// 3

Assert.assertTrue(mp.powerOfN(27, 3));

Assert.assertTrue(mp.powerOfN(9, 3));

Assert.assertTrue(mp.powerOfN(3, 3));

Assert.assertTrue(mp.powerOfN(1, 3));

Assert.assertFalse(mp.powerOfN(-1, 3));

Assert.assertFalse(mp.powerOfN(-3, 3));

Assert.assertFalse(mp.powerOfN(257, 3));

}

@Test

public void testPow() {

MathPower mp = new MathPower();

Assert.assertEquals(1, mp.pow(1, 4));

Assert.assertEquals(16, mp.pow(2, 4));

Assert.assertEquals(81, mp.pow(3, 4));

Assert.assertEquals(625, mp.pow(5, 4));

Assert.assertEquals(27, mp.pow(3, 3));

Assert.assertEquals(9, mp.pow(3, 2));

Assert.assertEquals(1, mp.pow(3, 0));

Assert.assertEquals(1, mp.pow(4, 0));

}

}

标签:assertTrue,3616,pow,Assert,mp,assertEquals,powerOfN
From: https://blog.51cto.com/fansunion/6056772

相关文章

  • 3616、4的幂
    给定一个整数,写一个函数来判断它是否是4的幂次方。如果是,返回true;否则,返回false。整数n是4的幂次方需满足:存在整数x使得n==4x示例1:输入:n=16输出:true示例......