Leetcode 2469. Convert the Temperature
You are given a temperature in Celsius. You need to convert this temperature to Kelvin and Fahrenheit using the following formulas:
Implement a function that takes a temperature in Celsius and returns an array containing the temperature in Kelvin and the temperature in Fahrenheit.
public class Solution {
public double[] convertTemperature(double celsius) {
// Convert Celsius to Kelvin
double kelvin = celsius + 273.15;
// Convert Celsius to Fahrenheit
double fahrenheit = celsius * 1.80 + 32.00;
// Return the resultant temperatures in an array
return new double[] {kelvin, fahrenheit};
}
public static void main(String[] args) {
Solution sol = new Solution();
// Test cases
double[] result1 = sol.convertTemperature(25.0);
System.out.println("Kelvin: " + result1[0] + ", Fahrenheit: " + result1[1]); // Expected: Kelvin: 298.15, Fahrenheit: 77.00
double[] result2 = sol.convertTemperature(-273.15);
System.out.println("Kelvin: " + result2[0] + ", Fahrenheit: " + result2[1]); // Expected: Kelvin: 0.00, Fahrenheit: -459.67
}
}
convertTemperature
which takes a double representing the temperature in Celsius.The time complexity for this problem is O(1) (constant time) since the computations involved (addition and multiplication) take a consistent amount of time regardless of the input size. The space complexity is also O(1) since we are using a fixed amount of additional space to store the results.
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?