본문 바로가기
코딩 테스트/알고리즘

알고리즘 7번 - js, c++

by GREEN나무 2024. 11. 12.
728x90

JS

문제

정수 num1과 num2가 매개변수로 주어질 때, num1을 num2로 나눈 값에 1,000을 곱한 후 정수 부분을 return 하도록 soltuion 함수를 완성해주세요.

제한사항
0 < num1 ≤ 100
0 < num2 ≤ 100


계획

계산 후  Math.trunc()써서 정수만 반환하


참고, 풀이

 Math.trunc();


function solution(num1, num2) {
    return Math.trunc(num1 / num2 *1000)
}

코드 간략화하기

function solution(num1, num2) {
    return Math.trunc((num1 * 1000) / num2);
}
// 가독성이 이게 좋데요

출처 

 

정수 반환 : https://s-logger.tistory.com/381#:~:text=JavaScript%EC%97%90%EC%84%9C%20Math.trunc(),%EA%B2%BD%EC%9A%B0%EC%97%90%20%ED%8A%B9%ED%9E%88%20%EC%9C%A0%EC%9A%A9%ED%95%A9%EB%8B%88%EB%8B%A4.


 

◆ C++

 

참고, 풀이

 

#include <string>
#include <vector>

using namespace std;

int solution(int num1, int num2) {
    double n = num1 / num2 *1000;
    int answer = n;
    return answer;
}

결과값이 1000

매게변수도 실수로 만들고 계산하기


#include <string>
#include <vector>

using namespace std;

int solution(int num1, int num2) {    
    double n = num1*1.0 / num2*1.0 *1000;
    int answer = n;
    return answer;
}



코드 간략화하기

#include <string>
#include <vector>

using namespace std;
int solution(int num1, int num2) {    
    return num1 * 1000 / num2;
}

실수로 바꿀필요 없이 미리 곱하고 나눈뒤에 정수형태로 반환


 

 

'코딩 테스트 > 알고리즘' 카테고리의 다른 글

알고리즘 9번 - js, c++  (0) 2024.11.12
알고리즘 8번 - js, c++  (0) 2024.11.12
알고리즘 6번- js, c++  (0) 2024.11.12
알고리즘 5번 -js, c++  (0) 2024.11.12
알고리즘 4번 - js, c++  (0) 2024.11.12