Calculate Simple Interest
Solve this ProblemEasy10 min
Topics
BasicsVariablesMath
Companies
TCSInfosysWipro
Given a
principal amount, an annual interest rate in percent, and a number of years, return the simple interest earned, formatted with two decimal places.
Simple interestSimple InterestInterest charged only on the original amount: principal × rate × years / 100. It does not compound. grows by the same amount every year, so the formula is a single line. The interesting part is choosing variable types. The product can reach five billion — too big for an int — and money should not pick up rounding errors. The first solution uses a double; the second keeps everything as whole numbers by counting in hundredths, which is exact.
Test Case 1:
Input:principal = 1000, rate = 5, years = 2
Output:"100.00"
Explanation:5% of 1000 is 50 per year, and two years make 100.
Test Case 2:
Input:principal = 1234, rate = 7, years = 3
Output:"259.14"
Explanation:1234 × 7 × 3 = 25914 hundredths, which is 259.14.
Constraints
- ◆
1 ≤ principal ≤ 1000000 - ◆
1 ≤ rate ≤ 100 - ◆
1 ≤ years ≤ 50
Try the Dry Run
Approach & Solutions
Floating-Point FormulaGood
Use the formula directly: interest = principal × rate × years / 100. Cast principal to double first, so the multiplication happens in floating point. That keeps the fraction from the division and also avoids int overflow, since the product can reach 5 billion. Format the answer with two decimal places.
Time
O(1)Space
O(1)Java
class Solution {
public String simpleInterest(int principal, int rate, int years) {
double interest = (double) principal * rate * years / 100;
return String.format("%.2f", interest);
}
}Exact Whole-Number ArithmeticOptimal
principal × rate × years is the interest measured in hundredths, because dividing by 100 is the last step. Keep that product as a 64-bit integer, split it with / 100 and % 100 into the whole part and the two decimal digits, and glue them together with a dot (with a leading zero when needed). No floating point is involved, so the answer is exact — the way money is usually handled.
Time
O(1)Space
O(1)Java
class Solution {
public String simpleInterest(int principal, int rate, int years) {
long hundredths = (long) principal * rate * years;
long whole = hundredths / 100;
long cents = hundredths % 100;
return whole + "." + (cents < 10 ? "0" : "") + cents;
}
}