题解 | #进制转换#

进制转换

https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String str = in.nextLine();
	  	//也可以只用一行代码解决,16表示转换为16进制
        //System.out.println(Integer.parseInt(str.substring(2),16));
        int t = 1,sum = 0;
        for(int i=2;i<str.length();i++){
            if(str.charAt(i) >= 'A' && str.charAt(i) <= 'F'){
                t = str.charAt(i) - 'A' + 10 ;
            }
            if(str.charAt(i) >= 'a' && str.charAt(i) <= 'F'){
                t = str.charAt(i) - 'a' + 10 ;
            }
            if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){
                t = str.charAt(i) - '0';
            }
            sum += function(t,str.length()-i-1);
        }
        System.out.println(sum);
    }

    //求16的y次方
    public static int function(int x,int y){
        int sum = 1;
        if(y==0){
            return x;
        }
        while(y>0){
            sum *= 16;
            y--;
        }
        return x*sum;
    }
}

全部评论

相关推荐

04-25 18:13
五邑大学 Java
后来123321:大二两段实习太厉害了,我现在大二连面试都没有
点赞 评论 收藏
分享
哥_留个offer先:跟他说,你这个最好用c#,微软就用c#Java不适合这个项目
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务