zoukankan      html  css  js  c++  java
  • 华为上机:求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;
        }
    }
  • 相关阅读:
    Topics
    telnetlib-telnet客户端操作
    logging-日志信息管理
    B.2 工具spy++
    B.1 XPath 获取技巧
    pyinstaller-将Python程序打包成一个独立可执行软件包
    探讨HTTP中敏感数据的安全性传输方案
    shell->一个经典的shell脚本结构
    c->再次封装已有函数的快速方法
    c->推荐的更安全的代码写法
  • 原文地址:https://www.cnblogs.com/theskulls/p/5706494.html
Copyright © 2011-2022 走看看