반응형
링크
https://school.programmers.co.kr/learn/courses/30/lessons/12943
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 설명 및 제한 조건
나의 코드
#include <string>
#include <vector>
using namespace std;
int solution(int num) {
int answer = 0;
long long temp = num; //int로 처리할 경우 데이터 범위 초과
while(num != 1) {
if(temp == 1) {
break;
}
if(temp % 2 == 0) {
temp = temp / 2;
} else {
temp = temp * 3 + 1;
}
answer++;
if(answer == 500) {
return -1;
}
}
return answer;
}
채점 결과
다수 코드
#include<iostream>
using namespace std;
int collatz(int num)
{
int answer = 0;
for (; answer < 500; ++answer) {
if (num == 1) { break; }
else if (num & 0x01) {
num *= 3;
num += 1;
} else {
num /= 2;
}
}
return answer >= 500? -1 : answer;
}
int main()
{
int testCase = 6;
int testAnswer = collatz(testCase);
cout<<testAnswer;
}
※삼항 연산자(조건 연산자)를 사용한 코드
반응형
'프로그래머스' 카테고리의 다른 글
[프로그래머스 C++] 가운데 글자 가져오기 (0) | 2022.10.01 |
---|---|
[프로그래머스 C++] 두 정수 사이의 합 (0) | 2022.09.28 |
[프로그래머스 C++] 하샤드 수 (0) | 2022.09.26 |
[프로그래머스 C++] 내적 (0) | 2022.09.24 |
[프로그래머스 C++] 정수 내림차순으로 배치하기 (0) | 2022.09.21 |