问题
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4058 访问。
给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。
输入: 16
输出: true
输入: 5
输出: false
进阶:你能不使用循环或者递归来完成本题吗?
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Given num = 16, return true.
Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
Credits:Special thanks to @yukuairoy for adding this problem and creating all test cases.
示例
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4058 访问。
public class Program { public static void Main(string[] args) { var n = 16; var res = IsPowerOfFour(n); Console.WriteLine(res); n = 257; res = IsPowerOfFour2(n); Console.WriteLine(res); Console.ReadKey(); } public static bool IsPowerOfFour(int num) { if(num <= 0) return false; while(num % 4 == 0) { num >>= 2; } return num == 1; } public static bool IsPowerOfFour2(int num) { while(num % 4 == 0 && (num >>= 2) > 1) { } return num == 1; } }以上给出2种算法实现,以下是这个案例的输出结果:
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4058 访问。
True False分析:
显而易见,以上2种算法的时间复杂度均为: 。
byteflying.com 认证博客专家 架构 设计模式 算法 86 年 dotnet 程序猿一枚,原公司技术主管、架构师,从事 10 多年 B/S、C/S 开发,现任西门子 .net 开发工程师,愿与大家分享些许个人经验,交流技术心得。另外欢迎大家访问我的小站【比特飞】:https://www.byteflying.com/