判断当前数值,是否为2的n次方

///   <summary>
        
///  主要思路
        
///  应用了位运算
        
///   </summary>
         public   static   void  FinB()
        {
            
int  n  =  Convert.ToInt32(Console.ReadLine());
            
if (n == 0 )
            {
                Console.WriteLine(
" N " );
                Console.ReadKey();
                
return ;
            }
            
if  (n  !=   1 )
            {
                
// n和n-1进行与运算,当n为4(二进制100),4-1为3(二进制11)值等于0,值为0时说明当前数值为2的N次方
                Console.WriteLine((n  &  (n  -   1 ))  ==   0   ?  (Convert.ToString(n,  2 ).Length  -   1   +   " Y " ) :  " N " );
            }
            
else
            {
                Console.WriteLine(
" Y " );
            }

            Console.ReadKey();
        }

 

你可能感兴趣的:(判断)