1094번 - 막대기
이건 시간초과가 나는 코드 입니다.
#include
using namespace std;
int main() {
cin.tie(NULL);
int x;
cin >> x;
int answer = 0;
while (1) {
answer += (x % 2);
x = (int)x / 2;
if (x == 1) {
answer++;
break;
}
cout << answer;
그리고 정답처리된 코드입니다.
#include #include #include using namespace std;int main() { cin.tie(NULL); int x; cin >> x; int answer = 0; if (x == 1) { cout << '1'; return 0; } while (x!=1) { answer += (x % 2); x = (int)x / 2; if (x == 1) { answer++; } } cout << answer;}
시간복잡도도 차이안나고
while이랑 break만
바뀐건데
왜 위에껀
시간초과가뜰까요?
x가 처음부터 1일 때 동작이 다릅니다.
앗 이런실수를.... 정말감사합니다
댓글을 작성하려면 로그인해야 합니다.
jooyeok42 4년 전 1
이건 시간초과가 나는 코드 입니다.
#include
#include
#include
using namespace std;
int main() {
cin.tie(NULL);
int x;
cin >> x;
int answer = 0;
while (1) {
answer += (x % 2);
x = (int)x / 2;
if (x == 1) {
answer++;
break;
}
}
cout << answer;
}
그리고 정답처리된 코드입니다.
#include
#include
#include
using namespace std;
int main() {
cin.tie(NULL);
int x;
cin >> x;
int answer = 0;
if (x == 1) {
cout << '1';
return 0;
}
while (x!=1) {
answer += (x % 2);
x = (int)x / 2;
if (x == 1) {
answer++;
}
}
cout << answer;
}
시간복잡도도 차이안나고
while이랑 break만
바뀐건데
왜 위에껀
시간초과가뜰까요?