I recently learned about the 20 most popular questions about C # on the Internet in Microsoft's virtual course. I want to write down my personal understanding and solutions for this question.
Subject:(Original) determine whether a number is a power of 2?
This is my own solution (a small console program) without looking at the correct answer. The Code is as follows:
static void Main(string[] args) { for (int increment = 0; increment < 100000; increment++) { if (IsPower(increment)) { Console.WriteLine(increment); } } Console.ReadKey(); } private static bool IsPower(int number) { bool result = false; if (number <= 0 || number % 2 == 1) return false; if (number / 2 > 1) { result = IsPower(number / 2); } else { result = number % 2 == 0; } return result; }
View code
My solution is to use a recursive method to call myself and determine whether the last call method is a power.
The solutions provided by Microsoft are as follows:
static void Main(string[] args) { for (int increment = 0; increment < 100000; increment++) { if (isPowerFromMic(increment)) { Console.WriteLine(increment); } } Console.ReadKey(); } private static bool isPowerFromMic(int number) { return number >1 && ((number & (number - 1)) == 0); }
View code
After reading their solutions, I felt that my solutions were weak and explosive! This idea depends on the binary principle of the computer, for example:
I will briefly explain that when the first digit is always 1 after each forward and last step, and the digits are all 0, for example, 8 & 7 = 0. It is easy to understand.
From this, you can use questions to get a question (Microsoft's method seems to be not conducive to expansion and slightly modified its code ):
Determines whether an integer is the power of another number? What about 2?
static void Main(string[] args) { while (true) { int baseNumber = Int32.Parse(Console.ReadLine()); int powerNumber = Int32.Parse(Console.ReadLine()); Console.WriteLine(IsPower(baseNumber, powerNumber)); } } private static bool IsPower(int number, int powerNumber) { bool result = false; if (number <= 0 || number % powerNumber != 0) return false; if (number / powerNumber > 1) { result = IsPower(number / powerNumber, powerNumber); } else { result = number % powerNumber == 0; } return result; }
View code
Determines whether an integer is the power of another integer.