9月13日微众银行笔试代码
1.拼接数字:数字统一转成String,后续处理比较方便,首先按字符串长度和字典序排序,从里面找出最大的三个数存到另一个数组中,然后按字典序排序,最后拼接即可得到答案
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] nums = new String[n]; for (int i = 0; i < n; i++) { nums[i] = sc.next(); } Arrays.sort(nums, (o1, o2) -> { if ( o1.length()==o2.length() ) { return o1.compareTo(o2); } else return o1.length()-o2.length(); }); String[] temp = new String[]{nums[n-1],nums[n-2],nums[n-3]}; Arrays.sort(temp); StringBuilder ans = new StringBuilder(); for (int i = temp.length - 1; i >= 0; i--) { ans.append(temp[i]); } System.out.println(ans); } }2.最少变换次数:如果能够变换,则较大的数一定是较小的数的2次幂,找到这个倍数关系即可轻松解答
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long a,b; while ( n-->0 ) { int ans = Integer.MAX_VALUE; a = sc.nextLong(); b = sc.nextLong(); long x = Math.max(a,b); long y = Math.min(a,b); if ( x==y ) ans = 0; // 判断能否整除 else if ( x%y!=0 ) ans = -1; else { // 判断x是否是y的2次方 long t = x/y; int cnt = 0; while ( t>1 ) { if ( t%2==1 ) { ans = -1; break; } t /= 2; cnt++; } if ( ans!=-1 ) { ans = 0; ans += cnt/3; cnt %= 3; ans += cnt/2; cnt %= 2; ans += cnt; } } System.out.println(ans); } } }3.上升子序列:(未AC,纯暴力+剪枝)
import java.util.*; public class Main { static long ans = 0,mod = 998244353; static int[] dp; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n,m; n = sc.nextInt(); m = sc.nextInt(); dp = new int[n]; dfs(new int[n],0,n,m); System.out.println(ans%mod); } public static void dfs( int[] nums,int index,int n,int m ) { int length = lis(nums,index); if ( length>3 ) return; if ( n-index<3-length ) return; if ( index==n ) { if ( length==3 ) ans++; return; } for (int i = 1; i <= m; i++) { nums[index] = i; dfs(nums,index+1,n,m); } } // 求最长上升子序列 public static int lis( int[] nums,int cnt ) { if ( cnt<2 ) return cnt; int res = 1; Arrays.fill(dp,1); for (int i = 1; i < cnt; i++) { for (int j = 0; j < i; j++) { if ( nums[i]>nums[j] ) { dp[i] = Math.max(dp[j]+1,dp[i]); } } res = Math.max(res,dp[i]); } return res; } }