2021-08-16阿里校招笔试:编写编译器,计算代码字节数
2021-08-16 笔试情况
题目:编写一个编译器,结算内存所需要的字节数 请输入一个字符串,编译出代码所需要的字节数,如:int a[10][10][10],k,m; int 类型所占4个字节 long 类型所占8个字节 char 类型所占1个字节 输入描述: int a[10][10][10],k,m; 输出描述: 输入格式为 变量类型+一个空格+变量; 输出结果: 4008 (10 x 10 x 10 + 1 + 1) x 4 = 4008
个人写的很丑很臭代码:
package kaoshi; import java.util.Arrays; import java.util.Scanner; /** * @author 王一宁 * @date 2021/8/16 18:34 * 【供阿里笔试 考试使用】 */ public class KaoShi { public static void main(String[] args) { int res = 0; //定义字节数 Scanner sc = new Scanner(System.in); String s = sc.nextLine(); String substring = s.substring(0, s.length() - 1); String[] chars1 = substring.split(" "); // 切割chars1 String[] splitchars1 = chars1[1].split(","); String stringnum = ""; int num = 0; // 数组乘几次 int baseNum = 0;// 求次方的底数 if (chars1[1].contains("[")){ for (int i = 0; i < splitchars1.length; i++) { if (splitchars1[i].contains("[")){ stringnum = splitchars1[i]; } } int i1 = stringnum.indexOf("["); System.out.println("第一次出现 [ 的下标: "+i1); int i2 = stringnum.indexOf("]"); System.out.println("第一次出现 ] 的下标: "+i2); String substringnum = stringnum.substring(i1 + 1, i2); baseNum = Integer.parseInt(substringnum); System.out.println("i3的数值为: "+baseNum); if (chars1[0].equals("int")) { for (int i = 0; i < stringnum.length(); i++) { char c = stringnum.charAt(i); if (c == '['){ num = num + 1; } } System.out.println("数值部分需要进行几次乘积:"+num); baseNum = (int) Math.pow(baseNum,num); res = (baseNum + splitchars1.length-1)*4; System.out.println("最终字节大小为: "+ res); }else if(chars1[0].equals("long")){ for (int i = 0; i < stringnum.length(); i++) { char c = stringnum.charAt(i); if (c == '['){ num = num + 1; } } System.out.println("数值部分需要进行几次乘积:"+num); baseNum = (int) Math.pow(baseNum,num); res = (baseNum + splitchars1.length-1)*8; System.out.println("最终字节大小为: "+ res); }else { for (int i = 0; i < stringnum.length(); i++) { char c = stringnum.charAt(i); if (c == '['){ num = num + 1; } } System.out.println("数值部分需要进行几次乘积:"+num); baseNum = (int) Math.pow(baseNum,num); res = baseNum + splitchars1.length-1; System.out.println("最终字节大小为: "+ res); } }else{ if (chars1[0].equals("int")){ res = splitchars1.length * 4; System.out.println(res); }else if (chars1[0].equals("long")){ res = splitchars1.length * 8; System.out.println(res); }else if (chars1[0].equals("char")){ res = splitchars1.length; System.out.println(res); } } } }
输出结果测试: