Convert Celsius to Fahrenheit
Solve this ProblemEasy5 min
Topics
BasicsVariablesMath
Companies
TCSInfosysWipro
Given a temperature in degrees
celsius, return the same temperature in Fahrenheit, formatted with two decimal places.
The conversion multiplies by 9/5 and adds 32. It is a short formula with a classic trap for beginners: in Java, C and C++, 9 / 5 is integer divisionInteger DivisionDividing two whole numbers and keeping only the whole part — 9 / 5 gives 1, not 1.8. and equals 1. Both solutions avoid it — one by dividing by 5.0, the other by using the ready-made factor 1.8. Formatting to two decimals also hides the tiny floating-point errorFloating-Point ErrorA tiny inaccuracy caused because most decimal fractions (like 1.8) cannot be stored exactly in binary. that decimal arithmetic can leave behind.
Test Case 1:
Input:celsius = 37
Output:"98.60"
Explanation:Normal body temperature: 37 × 9 / 5 = 66.6, plus 32.
Test Case 2:
Input:celsius = -40
Output:"-40.00"
Explanation:The one temperature that reads the same on both scales.
Constraints
- ◆
-273 ≤ celsius ≤ 1000
Try the Dry Run
Approach & Solutions
Multiply by 9, Then Divide by 5.0Good
Apply F = C × 9 / 5 + 32. The trap is 9 / 5: between two ints it equals 1, which would make every answer wrong. Dividing by 5.0 (a double) forces a decimal division. Python 3's / and JavaScript's / are always decimal, so they can use 5 directly.
Time
O(1)Space
O(1)Java
class Solution {
public String celsiusToFahrenheit(int celsius) {
double fahrenheit = celsius * 9 / 5.0 + 32;
return String.format("%.2f", fahrenheit);
}
}Use the 1.8 FactorOptimal
9 / 5 is exactly 1.8, so multiply by 1.8 and add 32. Because 1.8 is a double literal, the whole expression is decimal arithmetic automatically — there is no integer-division trap to fall into.
Time
O(1)Space
O(1)Java
class Solution {
public String celsiusToFahrenheit(int celsius) {
double fahrenheit = celsius * 1.8 + 32;
return String.format("%.2f", fahrenheit);
}
}