在Leetcode上看到一道题目:
Given an integer (singed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16
Output: true.
Example 2:
Input: 5
Output: false.
其实这道题,博主之前有做过类似的,就是判断是不是被3整除。其实原理都是一样,而且方法都是一样。这就直接进入代码环节了
class Solution {
public boolean isPowerOfFour(int num) {
String Change = Integer.toString(num,4);
boolean Four = Change.matches("^10*$");
return Four;
}
}
另外再附上其他java 写法:
class Solution {
public boolean isPowerOfFour(int num) {
if(num<1)
return false;
while(num % 4 == 0) {
num/=4;
}
return num==1;
}
}
如果想看博主之前写的Power of Three,就点击这里.
如果有哪里写错了,请指出来哦!如果觉得写的不错,就点个赞呗。你们的点赞是对博主的支持哦!