Determines whether an integer is the power of another integer.
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. question: (original) judge 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: copy the code 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 = n Umber % 2 = 0;} return result;} copy the code. My solution is to use recursive methods to call myself, determine whether the last method called is a power value of either 1 or 0. the following is a solution provided by Microsoft: copy the code 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-1) = 0 );} copy the code and read it. After our solutions, we feel that our solutions are weak and explosive! This idea is still based on the binary principle of the computer. I will briefly explain that when the first digit is always 1 after each forward and last digit is 0, for example, 8 & 7 = 0. I believe it is easy to understand. from this, I can draw on questions and wonder if I can come up with a question (Microsoft's method seems to be not conducive to expansion, slightly modifying its own code): How can I judge whether an integer is the power of another number? What about 2? Copy the code 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 ;}