프로그래밍
프로그래머스 C# 두 정수 사이의 합(삼항연산자, JAVA)
노마드선샤인
2023. 1. 21. 14:56
728x90
public class Solution {
public long solution(int a, int b) {
long answer = 0;
while (a != b)
{
answer += a;
a = (a > b) ? a - 1 : a + 1; /// a가 b보다 크면 a를 감소시켜서 b까지 되게 하고, 안 그러면 증가시켜서 b와 같게 한다.
}
return answer + b;
}
}
자바(등차수열의 합 공식 > (마지막 항 + 첫 항)/2 * 배열 갯수
class Solution {
public long solution(int a, int b) {
return sumAtoB(Math.min(a, b), Math.max(b, a));
}
private long sumAtoB(long a, long b) {
return (b - a + 1) * (a + b) / 2;
}
}
class Solution {
public long solution(int a, int b) {
long answer = 0;
if (a < b)
{
for (int i = a; i <= b; i++)
{
answer += i;
}
}
else
{
for (int i = b; i <= a; i++)
{
answer += i;
}
}
return answer;
}
}
class Solution {
public long solution(int a, int b) {
long answer = 0;
for (int i = ((a < b) ? a : b); i <= ((a < b) ? b : a); i++)
answer += i;
return answer;
}
}
728x90