0

Some phone usage rate may be described as follows:

The first minute of a call costs min1 cents.

Each minute from the 2nd up to 10th (inclusive) costs min2_10 cents each minute.

After the 10th minute, the call costs min11 cents for every additional minute.

You have s cents on your account before the call. What is the duration of the longest call (in minutes rounded down to the nearest integer) you can have?

Input data:

For min1 = 3, min2_10 = 1, min11 = 2, and s = 20, the output should be phoneCall(min1, min2_10, min11, s) = 14.

Here's why:

The first minute costs 3 cents, which leaves you with 20 - 3 = 17 cents. The total cost of minutes 2 through 10 is 1 * 9 = 9, so you can talk 9 more minutes and still have 17 - 9 = 8 cents. Each next minute costs 2 cents, which means that you can talk 8 / 2 = 4 more minutes. Thus, the longest call you can make is 1 + 9 + 4 = 14 minutes long.

I'm not sure what's wrong with my code's logic here.

int phoneCall(int min1, int min2_10, int min11, int s) {
    int sum = 0;

    if (s >= min1) {
        sum++;
        s = s - min1;
        for (int i = 1; i <= 9; i++) {
            if (s >= min2_10) {
                sum = sum++;
                s = s - min2_10;
            } else
                break;
        }
        sum = sum + s / min11;

    }
    return sum;
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
Shubham Sahay
  • 113
  • 1
  • 2
  • 8
  • you can simplify your life a lot by making a sub-method int totalMinutesPossible(rate, money, maxMinutes). Run this over each phone charge segment consecutively (subtracting what you needed to pay for the previous segment) until you run out of money. – ControlAltDel Jul 26 '18 at 20:22

3 Answers3

2

In the if statement inside of your for loop you can do one of two things here to get your return to be 14.

Change the sum=sum++; to sum += 1; or remove the sum= so it its just sum++;

This should return 14 as the sum.

Jaybro90
  • 104
  • 1
  • 12
0
            sum=sum++;

should be replaced with sum++;

Read more about operator precedence operator precedence and return values

Prabhu
  • 3,434
  • 8
  • 40
  • 48
-1

Hello @ShubhamSahay You gotta make your code like this:

public static int phoneCall(int min1, int min2_10, int min11, int s) {
int sum=0;

if(s>=min1)
{
    sum++;
    s=s-min1;
    for(int i=1;i<=9;i++)
    {
        if(s>=min2_10)
            {
            /*Change 1*/ sum++;
            s=s-min2_10;
            }
        else
            break;
    }
    /*Change 2*/ sum=sum+(s/min11);             

} 
return sum;
}

So here is why
1st Change: You need to do just sum++
2nd Change: you gotta put those that things in brackets

CodingWithAdin
  • 307
  • 1
  • 7
  • 18