欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

蓝桥杯十进制转十六进制

程序员文章站 2022-06-28 17:06:49
蓝桥杯十进制转十六进制基本思路是取余法,通过不断取余从后往前得到十六进制。import java.util.*;public class Main {public static void main(String[] args) {//存取十六进制String c[] = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};Scanner input = new Scanner(System.in);/...

蓝桥杯十进制转十六进制

基本思路是取余法,通过不断取余从后往前得到十六进制。

import java.util.*;
public class Main {
	public static void main(String[] args) {
		//存取十六进制
		String c[] = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
		Scanner input = new Scanner(System.in);//设置输入
		double a = input.nextDouble(); //输入double类型
		StringBuffer o = new StringBuffer(""); //字符串变量
		int x;
		String y;
		if(a>0) {
			//零的情况比较特殊
			while(a>=1) {
				x = (int)a%16; //通过取余获得最后一位
				y = c[x]; //获取得到的某一位十六
				//往第一位不断插入
				o.insert(0, y);   //StringBuffer的方法
				a/=16;			//语法:字符串变量.insert(索引值(插入到那个位置前面),插入值)
			}
		}else {
			o.append(0);
		}
		System.out.println(o);
	}
}

主要是靠StringBuffer类的应用,相对于c++的String有较大的优势。
StringBuffer类还有很多方法,比较常用的有append(往后边插入),insert(往特定位置插入),reverse(反转,从后往前),delete(删除特定位置)。

本文地址:https://blog.csdn.net/weixin_45924425/article/details/109575813