腾讯云智三道算法题
/第三题 1234 000 001 010 011 101 110 111。////第二题-数组 ,初始长度。//第一题:一个水果切成n块。
·
import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class MyMain { //第一题:一个水果切成n块 public static void getRes(int n, int l, int r){ int min = -1; int max = -1; for (int i=l;i<=r;i++){ if (i%n==0){ min = i/n; break; } } for (int i=r;i>=l;i--){ if (i%n==0){ max=i/n; break; } } if (min==-1||max==-1){ System.out.println(-1); }else{ System.out.println(min+" "+max); } } // //第二题-数组 ,初始长度 // //9 1 // //9 5 8 1 3 2 7 6 4 // public static void getTwoRes(int[] nums, int len){ // int n = nums.length; // Arrays.sort(nums); // if (nums[0]>len){ // System.out.println(len); // return; // } // int index = 0; // while (index<n&&nums[index]<=len){ // len++; // index++; // } // System.out.println(len); // } // // public static void main(String[] args) { // Scanner scanner = new Scanner(System.in); // int N = scanner.nextInt(); // int L = scanner.nextInt(); // int[] nums = new int[N]; // for (int i=0;i<N;i++){ // nums[i]=scanner.nextInt(); // } // getTwoRes(nums,L); // } //[1,2] //第三题 1234 000 001 010 011 101 110 111 public static void getResThree(String s){ int n = s.length(); int num = (int) Math.pow(2,n-1); List<List<Integer>> res = new ArrayList<>(); int result = 0; for (int i=0;i<num;i++){ List<Integer> ls = new ArrayList<>(); for (int j=0;j<n-1;j++){ if (((i>>j)&1)==1){ ls.add(1); }else{ ls.add(0); } } res.add(ls); } for (int i=0;i<res.size();i++){ StringBuilder stringBuilder = new StringBuilder(s); int count = 1; for (int j=0;j<res.get(i).size();j++){ if (res.get(i).get(j)==1){ stringBuilder.insert(count,"+"); count+=2; }else{ count+=1; } } String[] split = stringBuilder.toString().split("\\+"); long mySum=0; for (int k=0;k<split.length;k++){ mySum += Long.parseLong(split[k]); } if (isPrime(mySum)){ result++; } } System.out.println(result); } public static boolean isPrime(long n){ if (n==1){ return false; } if (n==2){ return true; } for (int i=2;i<n;i++){ if (n%i==0){ return false; } } return true; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); getResThree(scanner.nextLine()); } // public static void main(String[] args) { // Scanner scanner = new Scanner(System.in); // int N = scanner.nextInt(); // int L = scanner.nextInt(); // int[] nums = new int[N]; // for (int i=0;i<N;i++){ // nums[i]=scanner.nextInt(); // } // getTwoRes(nums,L); // } }
更多推荐
所有评论(0)