비트를 쪼개는 개발자

allen321@naver.com

코딩테스트

C# [프로그래머스] 음양 더하기

MozarTnT 2024. 5. 9. 16:14
728x90
반응형

 

 

 

 

 

absolutes 라는 int 배열을 받아와서 signs의 배열 값이 true 일 경우 양수, false 일 경우 음수로 absolutes의 숫자를 변경하고 이를 모두 합한 숫자를 answer로 반환하면 되는 문제다.

 

public static void Main()
{
    int[] absolutes = new int[] { 4, 7, 12 }; // 숫자 배열
    bool[] signs = new bool[] { true, false, true }; // 음양 결정 bool 값

    Console.WriteLine(Solution(absolutes, signs));
}

public static int Solution(int[] absolutes, bool[] signs)
{
    int answer = 0;

    for(int i = 0; i < absolutes.Length; i++) // 숫자 배열 길이만큼
    {
        if (signs[i] == true) // bool값이 참이면
        {
            answer += absolutes[i]; // answer 에 양수를 더함
        }
        else // bool값이 false면
        {
            answer += absolutes[i] * -1; // 값에 -1을 곱해서 더함 (음수로 만듬)
        }
    }
    return answer;
}
728x90
반응형