zoukankan      html  css  js  c++  java
  • 程序片段--2的乘方

       1. 2的10次方是多少?

        2.65536是2的多少次方?

        算着太累,折腾了一个小片段。

     1 public class Sum2 {
     2     final static  int count =2;
     3     //输入2的次方,获得2的次方的结果
     4     public static int sum2(int loop){
     5         int result=1;
     6         if(loop<0){
     7             return 1;
     8         }else{
     9             while(loop>0){
    10                 result*=count;
    11                 loop--;
    12             }  
    13         }
    14               
    15         return result;
    16     }
    17     //输入2的倍数,获得2的次方数
    18     public static int sum3(int result){
    19         int ct=0;
    20 if(result % count != 0 || result<0){ 21 System.out.print("error = "); 22 return result; 23 }else{ 24 while(result != 1){ 25 result /= count ; 26 ct++; 27 } 28 } 29 return ct; 30 } 31 public static void main(String[] args) { 32 System.out.println(sum2(4)); 33 System.out.println(sum3(16)); 34 } 35 }

    PS:判断一个数是否是2的次方---想法太牛了。

     1     //判断一个数是否是2的次方。
     2     public static boolean checked(int n)
     3     {
     4         if (n < 0)
     5             return false;
     6         if (n < 2)
     7             return false;
     8 
     9         return (n & (n - 1)) == 0;
    10     }
     1 public static bool Check2(int num)
     2 {
     3     if (num == 1)
     4         return true;
     5     else
     6     {
     7         do
     8         {
     9             if (num % 2 == 0)
    10                 num = num / 2;
    11             else
    12                 return false;
    13         }
    14         while (num != 1);
    15         return true;
    16     }
    17 }
    1     public static boolean checked(int x)
    2     {
    3         return (x != 0) && ((x & (x - 1)) == 0);
    4     }
  • 相关阅读:
    [Matlab.Matrix] 作为判断条件
    [Matlab.GUI] 学习小结
    [Modelsim] 初识
    [Matlab] isnan
    [Matlab] round
    [VS2012] 无法查找或打开 PDB 文件
    [Matlab.GUI]初识
    表格特效代码全集中
    JAVASCRIPT基础
    第4天:调用样式表
  • 原文地址:https://www.cnblogs.com/maduar/p/4379653.html
Copyright © 2011-2022 走看看