-
수열의 사칙연산알고리즘/알고리즘 퍼즐68 2020. 6. 3. 23:25
[문제]
나열된 각 숫자 사이에 사칙연산의 연산자를 넣어 계산한 결과가 원래 수를 거꾸로 나열한 숫자를 구하시오.
(1000 ~ 9999사이, 연산자를 넣지 않아도 되지만 최소한 하나는 넣는 것으로 한다.)
[언어]
Java(1.8)
[풀이]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384//연산자String[] operator = new String[] {"+", "x", "/" ,"-", ""};//1000 ~ 9999까지 4자리 수int n = 1000;while(n < 9999) {String num = String.valueOf(n);//숫자 저장 리스트List<Integer> numList = new ArrayList<>();//연산자 저장 리스트List<String> operatorList = new ArrayList<>();for(int i = 0; i < operator.length; i++) {for(int j = 0; j < operator.length; j++) {for(int k = 0; k < operator.length; k++) {String formula = num.charAt(0) + operator[i] + num.charAt(1) + operator[j] + num.charAt(2) + operator[k] + num.charAt(3);//연산자는 무조건 하나이상 들어가야 하므로 4자리는 연산자Xif(formula.length() == 4) {i++;continue;}String numStr = "";//숫자와 연산자를 구분하여 각 리스트에 addfor(int l = 0; l < formula.length(); l++) {String str = String.valueOf(formula.charAt(l));if("+x/-".contains(str)) {numList.add(Integer.parseInt(numStr));operatorList.add(str);numStr = "";}else {numStr += str;}}numList.add(Integer.parseInt(numStr));//자바스크립트의 경우 식을 그대로 실행 시켜주는 함수가 있음(eval)//자바에는 없기 때문에 계산 직접 구현//괄호가 없다는 가정하에 아래 로직이 정상 동작//ex) 1 + 2 x 3 => 1 + 6 + 0//ex) 1 + 6 / 3 => 1 + 2 + 0//ex) 1 - 2 - 2 => 1 + -2 + -2//모든 연산자를 + 로 바꿔주고 앞에서부터 더한다for(int l = operatorList.size() - 1; l >= 0; l--) {if(operatorList.get(l).equals("x")) {numList.set(l, numList.get(l) * numList.get(l+1));numList.set(l+1, 0);operatorList.set(l, "+");}else if(operatorList.get(l).equals("/")) {if(numList.get(l+1) != 0) {numList.set(l, numList.get(l) / numList.get(l+1));}numList.set(l+1, 0);operatorList.set(l, "+");}else if(operatorList.get(l).equals("-")) {numList.set(l+1, numList.get(l+1) * -1);operatorList.set(l, "+");}}int result = 0;for(int l = 0; l < numList.size(); l++) {result += numList.get(l);}String resultStr = String.valueOf(result);if(resultStr.length() == 4) {if(num.charAt(0) == resultStr.charAt(3) && num.charAt(1) == resultStr.charAt(2)&& num.charAt(2) == resultStr.charAt(1) && num.charAt(3) == resultStr.charAt(0)) {System.out.println(num);n = 9999;}}numList.clear();operatorList.clear();}}}n++;}}cs [답]
5931
(5x9x31 = 1395)
'알고리즘 > 알고리즘 퍼즐68' 카테고리의 다른 글
카드를 뒤집어라! (0) 2020.06.10 앞뒤가 같은 10진수 만들기 (0) 2020.05.31