본문 바로가기

프로그래머스/lv1

내적

/* 내적
 * 길이가 같은 두 1차원 정수 배열 a, b가 매개변수로 주어집니다.
 * a와 b의 내적을 return 하도록 solution 함수를 완성해주세요.
 *
 * a            b           result
 * [1,2,3,4]    [-3,-1,0,2] 3       1*(-3) + 2*(-1) + 3*0 + 4*2 = 3
 * [-1,0,1]     [1,0,-1]    -2      (-1)*1 + 0*0 + 1*(-1) = -2
 */
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class programmer_1_29 {
    static int[] a1 = {1,2,3,4};    static int[] b1 = {-3,-1,0,2};
    static int[] a2 = {-1,0,1};     static int[] b2 = {1,0,-1};
    public int solution(int[] a, int[] b) {
        int answer = 0;
        for(int i = 0; i < a.length; i++){
            answer += a[i] * b[i];
        }
        return answer;
    }
    public static void main(String args[]){
        programmer_1_29 t = new programmer_1_29();
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a1,b1));
        System.out.println("---------------------------------------");
        System.out.println("result2 = " + t.solution(a2,b2));
        System.out.println("---------------------------------------");
    }
}
cs

'프로그래머스 > lv1' 카테고리의 다른 글

약수의 개수와 덧셈  (0) 2022.12.19
문자열 내림차순으로 배치하기  (0) 2022.12.19
수박수박수박수박수박수?  (0) 2022.12.14
가운데 글자 가져오기  (0) 2022.12.14
없는 숫자 더하기  (0) 2022.12.14