프로그래머스 문제풀이/LEVEL 2

[C++] 프로그래머스 문제풀이 LEVEL 2 우박수열 정적분

코딩준우 2023. 7. 5. 13:09

 

https://school.programmers.co.kr/learn/courses/30/lessons/134239

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<double> solution(int k, vector<vector<int>> ranges) {
    vector<double> answer;
    vector<double> areas;
    double sum = 0.0;
    double area;
    int x = 0, y = k;
    areas.push_back(0.0);
    while(y != 1)
    {
        int pre = y;
        if (y % 2 == 0)
            y /= 2;
        else
            y = 3 * y + 1;
        x++;
        
        area = (pre + y) / 2.0;
        sum += area;
        areas.push_back(sum);
    }
    
    for (int i = 0; i < ranges.size(); ++i)
    {
        int s = ranges[i][0];
        int e = areas.size() + ranges[i][1] - 1;
        
        if(s > e)
            answer.push_back(-1.0);
        else if (s == e)
            answer.push_back(0.0);
        else
            answer.push_back(areas[e] - areas[s]);   
    }
    return answer;
}