1.字符串分割
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
String str=sc.nextLine();
StringBuilder sb=new StringBuilder();
sb.append(str);
int size=str.length();
int addZero=8-size%8;
while((addZero>0&&(addZero<8))){
sb.append("0");
addZero--;
}
String str1=sb.toString();
while(str1.length()>0){
System.out.println(str1.substring(0,8));
str1=str1.substring(8);
}
}
用StringBulider进行存储,append函数补位,输出依次截取8位
2.进制转换
进制转换都能学几百遍了,还是继续不会写代码
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
String s = sc.nextLine();
System.out.println(Integer.parseInt(s.substring(2,s.length()),16));
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
String str=sc.nextLine();
String num=str.substring(2,str.length());
int result=0;
int power=1;
for (int i=num.length()-1;i>=0;i--){
char c=num.charAt(i);
if(c>='0'&&c<='9'){
result+=(c-'0')*power;
}else if(c>='A'&&c<='F'){
result+=(c-'A'+10)*power;
}
power *=16;
}
System.out.println(result);
}
sc.close();
}
扩展:
十进制转二进制
public static void main(String[] args) {
int number;
Scanner sc=new Scanner(System.in);
ArrayList<String> binary=new ArrayList<String>();
System.out.println("Enter a decimal number:");
number =sc.nextInt();
while(number!=0){
binary.add(String.valueOf(number%2));
number/=2;
}
Collections.reverse(binary);
System.out.print("Binary number is: ");
for(String s:binary){
System.out.print(s);
}