两道题目,第一题使用for循环嵌套,可以的话将代码和运行结果一起截图,并给一下可复制的代码
3条回答 默认 最新
- 广大菜鸟 2021-10-14 21:11关注
import java.util.Collections; import java.util.HashSet; import java.util.Set; public class Solution { public static int[] firstHelper(){ /* a + b - 9 == 4 || a + c / f == 4|| b - d * g == 4|| c - d * e == 4|| 9 - e - h == 4|| f + g - h == 4|| */ int []answer; for(int a=0;a<=9;a++){ for(int b=0;b<=9;b++){ if(a + b - 9 != 4) continue;//第一行 for(int c=0;c<=9;c++){ for(int d=0;d<=9;d++){ for(int e=0;e<=9;e++){ if( c - d * e != 4) continue;//第二行 for(int f=1;f<=9;f++){//f不能为0 if(a + c / f != 4) continue;// 第一列 for(int g=0;g<=9;g++){ if( b - d * g != 4) continue;//第二列 for(int h =0;h<=9;h++){ if( 9 - e - h == 4 && f + g - h == 4) {// 第三列、第三行 answer = new int[]{a, b, c, d, e, f, g, h}; return answer; } } } } } } } } } return new int[0]; } public static void firstQuestion(){ int[] answer = Solution.firstHelper(); if (answer.length > 0) { System.out.println(answer[0] + " " + answer[1]); System.out.println(answer[2] + " " + answer[3] + " " + answer[4]); System.out.println(answer[5] + " " + answer[6] + " " + answer[7]); } } public static boolean hasRepeat(int[] args){ Set tempSet = new HashSet(); for(int n:args){ tempSet.add(n); } if(args.length == tempSet.size()){ return false; }else{ return true; } } /* |a-b|>1 b < d c % 2 == 0 a - e == 3 c = 2 / 4 */ public static int[] secondHelper(){ int[] answer; for(int a=1+3; a<=5; a++){ for(int b=1;b<=5;b++) {//|a-b|>1 if (Math.abs(a - b) > 1) { for (int c = 2; c <= 5; c += 2) {//c%2==0 for (int d = b + 1; d <= 5; d++) {//d>b if (d > b) { for (int e = 1; e <= 5-3; e++) { if (a - e >= 3) { answer = new int[]{a, b, c, d, e}; if (!hasRepeat(answer)) return answer; } } } } } } } } return new int[0]; } public static void secondQuestion(){ int[] answer = Solution.secondHelper(); if (answer.length > 0) { for(int n:answer){ System.out.print(n+" "); } } } public static void main(String[]args){ Solution.firstQuestion(); Solution.secondQuestion(); } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 求差集那个函数有问题,有无佬可以解决
- ¥15 【提问】基于Invest的水源涵养
- ¥20 微信网友居然可以通过vx号找到我绑的手机号
- ¥15 寻一个支付宝扫码远程授权登录的软件助手app
- ¥15 解riccati方程组
- ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
- ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
- ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
- ¥50 树莓派安卓APK系统签名
- ¥65 汇编语言除法溢出问题