Similar Problems
Similar Problems not available
Convert The Temperature - Leetcode Solution
LeetCode: Convert The Temperature Leetcode Solution
Difficulty: Easy
Topics: math
Convert The Temperature is a problem on Leetcode that involves converting a temperature in Celsius to Fahrenheit.
The problem statement is as follows:
Given a temperature in Celsius, return the equivalent temperature in Fahrenheit. You need to round the answer to the nearest integer.
Note: You should not use any built-in function like ceil
, floor
, round
etc.
Example 1:
Input: temperature = 25 Output: 77 Explanation: Formula to convert Celsius to Fahrenheit is F = C × 9/5 + 32. Here C = 25, so it is (25 * 9/5) + 32 = 77.
Example 2:
Input: temperature = -5 Output: 23 Explanation: Formula to convert Celsius to Fahrenheit is F = C × 9/5 + 32. Here C = -5, so it is (-5 * 9/5) + 32 = 23.
To solve this problem, we need to understand the formula to convert Celsius to Fahrenheit, which is:
F = C × 9/5 + 32
where F is the temperature in Fahrenheit and C is the temperature in Celsius.
We also need to understand how to round the answer to the nearest integer without using any built-in functions. We can achieve this by adding 0.5 to the answer and then floor it using the integer division operator //
. This will round the answer to the nearest integer.
With that understanding, we can write the following Python code to solve the problem:
class Solution:
def celsiusToFahrenheit(self, temperature: int) -> int:
fahrenheit = temperature * 9/5 + 32
rounded_fahrenheit = fahrenheit + 0.5 // 1
return int(rounded_fahrenheit)
In this code, we first calculate the temperature in Fahrenheit using the formula. We then add 0.5 to the answer and use integer division to round it to the nearest integer. Finally, we return the rounded integer.
This solution has a time complexity of O(1) and a space complexity of O(1).
Convert The Temperature Solution Code
1