Calculate the Area of a Circle
Solve this ProblemEasy5 min
Topics
BasicsVariablesMath
Companies
TCSInfosysWipro
Given the
radius of a circle, return its area rounded to two decimal places.
The formula is the familiar πr². What makes it a variables-and-types exercise is π itself: it is not a whole number, so the area must live in a floating-pointFloating-Point NumberA number stored with a fractional part, such as a double. It can hold 3.14159… approximately. variable even though the radius is an int. Most languages provide π as a named constantNamed ConstantA fixed value given a readable name (like Math.PI) so you do not have to type its digits.; in C you define it yourself. The two solutions differ only in how the radius is squared.
Test Case 1:
Input:radius = 7
Output:"153.94"
Explanation:π × 49 ≈ 153.938, which rounds to 153.94.
Test Case 2:
Input:radius = 1
Output:"3.14"
Explanation:With radius 1 the area is π itself.
Constraints
- ◆
1 ≤ radius ≤ 10000
Try the Dry Run
Approach & Solutions
Multiply π by r × rOptimal
Area = π × r × r. Use the language's built-in π constant (Math.PI, math.pi, M_PI), multiply by the radius twice, and format the double to two decimal places. C has no standard π constant, so the C version defines its own with #define.
Time
O(1)Space
O(1)Java
class Solution {
public String circleArea(int radius) {
double area = Math.PI * radius * radius;
return String.format("%.2f", area);
}
}Square with a Power FunctionGood
Write the formula exactly as it appears in maths, πr², by squaring the radius with a power function (Math.pow, math.pow, pow). It always works with doubles. C's pow lives in a separate maths library that has to be linked in, so the C version writes a tiny power helper of its own: multiply 1 by the base, exponent times. For a square it is no faster than r × r, but it handles any exponent.
Time
O(1)Space
O(1)Java
class Solution {
public String circleArea(int radius) {
double area = Math.PI * Math.pow(radius, 2);
return String.format("%.2f", area);
}
}