Leetcode 2469. Convert the Temperature
Problem Statement
You are given a temperature in Celsius. You need to convert it to both Kelvin and Fahrenheit and return it in an array where:
- The first element is the temperature in Kelvin.
- The second element is the temperature in Fahrenheit.
Given a floating-point number celsius
representing the temperature in Celsius, you need to implement a function that returns the resulting temperatures in a list of two floating point numbers.
- To convert Celsius to Kelvin: ( K = C + 273.15 )
- To convert Celsius to Fahrenheit: ( F = C \times \frac{9}{5} + 32 )
Clarifying Questions
- Input Constraints:
- Are there any specific bounds on the value of the temperature in Celsius?
- The problem statement does not specify any bounds, but we will assume it is a valid floating-point number.
- Output Format:
- Should the conversion retain a certain number of decimal places, or is any floating-point precision acceptable?
- We will assume that any reasonable floating-point precision is acceptable unless otherwise specified.
Strategy
- Read the input temperature in Celsius.
- Convert the temperature to Kelvin using the formula ( K = C + 273.15 ).
- Convert the temperature to Fahrenheit using the formula ( F = C \times \frac{9}{5} + 32 ).
- Return the results in the specified array format
[Kelvin, Fahrenheit]
.
Code
#include <vector>
class Solution {
public:
std::vector<double> convertTemperature(double celsius) {
double kelvin = celsius + 273.15;
double fahrenheit = celsius * 9.0 / 5.0 + 32.0;
return {kelvin, fahrenheit};
}
};
Time Complexity
The time complexity for this solution is ( O(1) ), which is constant time. The reason is that only a fixed number of arithmetic operations are performed, irrespective of the input size.
Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI
-
Got blindsided by a question you didn’t expect?
-
Spend too much time studying?
-
Or simply don’t have the time to go over all 3000 questions?