-
정해진 범위 안에 배수 구하기.Algo 2018. 9. 20. 15:08코딩도장 이라는 곳에서 추천 첫번째 상단에 있는 문제를 풀었습니다.java로 풀었고 solution1은 제가 생각한 풀이법입니다.나머지 solution2,3은 추천수가 가장 높던 풀이법들입니다.
밑으로 내려 갈 수록 코드가 간결해지죠?
다른 코드를 보면서 숏코드 작성에 대하여 생각해보게되었습니다.
공배수 관련한 문제는 &&연산자 보다는 || 연산자로 조건을 만드는 것이 보기 편하고,
Java가 8버전까지 나오면서 좀더 간결한 연산이 가능하게 됨을 느꼈는데,
저런 방식을 람다식이라고 하지 않나요?
저도 사실 능숙하게 이용이 어려워서, 좀 더 공부해야 겠다고 생각하였습니다.
여기에 람다식과 스트림에 관한 내용이 정리가 되어있는데
나중에 한 번 찾아봐야겠어요.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters/* 10미만의 자연수에서 3과 5의 배수를 구하면 3,5,6,9이다. 이들의 총합은 23이다. 1000미만의 자연수에서 3,5의 배수의 총합을 구하라. */ import java.util.Scanner; import java.util.stream.IntStream; public class Coding_camp { static int answer =0; public static void main(String[] args){ Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int answer = solution3(num); System.out.println(answer); } private static int solution1(int num) { answer=0; for(int i=1;i<num;i++){ if(i%3==0 && i%5==0) answer+=i; else if(i%5==0) answer+=i; else if(i%3==0) answer+=i; } return answer; } private static int solution2(int num) { answer=0; for(int i=1;i<num;i++) if(i%3==0 || i%5==0) answer+=i; return answer; } private static int solution3(int num){ return IntStream.range(1,num).filter(answer-> answer%3==0 || answer%5==0).sum(); } } LIST'Algo' 카테고리의 다른 글
[LeetCode]Reverse Integer (0) 2019.06.22 [LeetCode] Climbing Stairs (0) 2019.05.06 [BOJ-2566]백준 알고리즘 2566 [Kotlin][Java] (0) 2019.04.28 [LeetCode] Two sum (0) 2019.03.10 [BOJ 2455] 백준 알고리즘 2455 (0) 2019.03.03