7.31科大讯飞四道编程题个人思路
讯飞四道编程题个人思路
第一题:
有面值1,5,10,50,100,分别对应变量:a、b、c、d、e
若有k元钱,最少多少张纸币能找零,若不能则输出-1
public class Main { public static int minMoney(int[] nums,int target){ int[] money = {1,5,10,50,100}; int count = 0; for (int i=4;i>=0;i--){ int shang = target/money[i]; int cur_temp = Math.min(nums[i],shang); count += cur_temp; target -= cur_temp * money[i]; if (target==0){ return count; } } return -1; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){ String[] s = scanner.nextLine().trim().split(" "); int[] nums = new int[s.length]; for (int i = 0; i < s.length; i++) { nums[i] = Integer.parseInt(s[i]); } int target = scanner.nextInt(); System.out.println( minMoney(nums,target)); scanner.nextLine(); } } }第二题:快排,自己注意处理一下输出
public class Main { public static void mySort(int[] nums,int low,int hight){ int i,j,temp,t; if(low>hight){ return; } i=low; j=hight; temp = nums[low]; while (i<j){ while (temp<nums[j] && i<j){ j--; } while (temp>=nums[i] && i<j){ i++; } if (i<j){ t = nums[j]; nums[j] = nums[i]; nums[i] = t; } } nums[low] = nums[i]; nums[i] = temp; prin(nums); System.out.println(); mySort(nums,low,j-1); mySort(nums,j+1,hight); } public static void prin(int[] nums){ for (int k = 0; k < nums.length; k++) { System.out.print(nums[k]); if (k!=nums.length-1){ System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){ int len = scanner.nextInt(); scanner.nextLine(); String[] s = scanner.nextLine().trim().split(" "); int[] nums = new int[s.length]; for (int i = 0; i < s.length; i++) { nums[i] = Integer.parseInt(s[i]); } mySort(nums,0,len-1); } } }第三题:判断给定对角坐标,两个矩形是否相交。
public class Main { /** * 解法一:逆向思维,找不相交的情况; * */ public static int isRectangleOverlap(int[] nums){ if (nums[2]<nums[4] || nums[0] > nums[6] || nums[1]>nums[7] || nums[3]<nums[5]){ return 0; } return 1; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){ String[] s = scanner.nextLine().trim().split(" "); int[] nums = new int[s.length]; for (int i = 0; i < s.length; i++) { nums[i] = Integer.parseInt(s[i]); } System.out.println(isRectangleOverlap(nums)); } } }
最后一题:从字符串中抽出整数,注意处理负号就行了
public class Main { public static void convertToInt(String s){ StringBuilder res = new StringBuilder(); int subFlag = 0; for (int i = 0; i < s.length(); i++) { if (res.length() ==0 && subFlag == 0 && s.charAt(i) == '-'){ subFlag = 1; res.append(s.charAt(i)); } if (s.charAt(i)>='0' && s.charAt(i)<='9'){ res.append(s.charAt(i)); } } System.out.println(Long.parseLong(res.toString())); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){ String s = scanner.nextLine(); convertToInt(s); } } }