• 华为上机:求2的N次幂的值


    求2的N次幂的值
    描述:

    求2的N次幂的值(N最大不超过31,用位运算计算,结果以十六进制进行显示)。

    运行时间限制: 无限制
    内存限制: 无限制
    输入:

    数字N

    输出:

    2的N次方(16进制,需要按照16进制格式进行显示)

    样例输入:
    5
    样例输出:
    0x20

    解题

    直接调用内部函数

    import java.util.Scanner;  
    public class Main{  
        static int count;  
        public static void main(String[] args){  
            Scanner in = new Scanner(System.in);  
            while(in.hasNext()){  
                int n = in.nextInt();  
                int pow = 2<<(n-1);  
                  
                String s = Integer.toHexString(pow);  
                System.out.println("0x"+s);  
            }  
              
            in.close();  
        }  
    }  

    自己实现2的n次方、16进制转换

    import java.util.Scanner;
    public class Main{
        public static void main(String[] args){
            Scanner in = new Scanner(System.in);
            while(in.hasNext()){
                int n = in.nextInt();
    //            int pow = 2<<(n-1); // 直接调用内部函数
    //            String s = Integer.toHexString(pow);
    //            System.out.println("0x"+s);
                
                long x = powan(2,n);
                String s2 = longToHex(x);
                System.out.println(s2);
            }
            
            in.close();
        }
        public static String longToHex(long x){
            String[] a = new String[]{"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E"};
            StringBuffer sb = new StringBuffer();
            while(x>0){
                int id = (int)x%16; //求余数,对于数组id 
                sb.insert(0, a[id]); // 插入到第0个位置
                x=x/16; // 更新
                
            }
            sb.insert(0, "0x");
            
            return sb.toString();
        }
        public static long powan(int a,int n){
            if(a==0)
                return 0;
            if(n==0)
                return 1;
            if(n==1)
                return a;
            long res = powan(a,n>>1); // 计算一半结果
            res*=res; // 偶数还是奇数都要相乘
            if((n&1)==1){ // 奇数时候多个 a 
                res *=a;
            }
            return res;
        }
    }
  • 相关阅读:
    js实现图片上传前预览
    WPF实现鼠标拖动控件并带有中间动效
    Redis 挂了自动重启的shell 脚本。
    PIE-Basic教程目录索引
    从零实现Linux一键自动化部署.netCore+Vue+Nginx项目到Docker中
    在BlazorWebAssembly中使用Autofac
    angular报错:Cannot assign to a reference or variable
    ASP.NET Core Logging Solution
    Typora + PicGo-Core + Custom Command 实现上传图片到图床
    mysql like多个
  • 原文地址:https://www.cnblogs.com/bbbblog/p/5706494.html
Copyright © 2020-2023  润新知