Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Apply Discount to Prices LeetCode Solution

Problem – Apply Discount to Prices LeetCode Solution

sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign.

  • For example, "$100""$23", and "$6" represent prices while "100""$", and "$1e5" do not.

You are given a string sentence representing a sentence and an integer discount. For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places.

Return a string representing the modified sentence.

Note that all prices will contain at most 10 digits.

Example 1:

Input: sentence = "there are $1 $2 and 5$ candies in the shop", discount = 50
Output: "there are $0.50 $1.00 and 5$ candies in the shop"
Explanation: 
The words which represent prices are "$1" and "$2". 
- A 50% discount on "$1" yields "$0.50", so "$1" is replaced by "$0.50".
- A 50% discount on "$2" yields "$1". Since we need to have exactly 2 decimal places after a price, we replace "$2" with "$1.00".

Example 2:

Input: sentence = "1 2 $3 4 $5 $6 7 8$ $9 $10$", discount = 100
Output: "1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$"
Explanation: 
Applying a 100% discount on any price will result in 0.
The words representing prices are "$3", "$5", "$6", and "$9".
Each of them is replaced by "$0.00".

Constraints:

  • 1 <= sentence.length <= 105
  • sentence consists of lowercase English letters, digits, ' ', and '$'.
  • sentence does not have leading or trailing spaces.
  • All words in sentence are separated by a single space.
  • All prices will be positive integers without leading zeros.
  • All prices will have at most 10 digits.
  • 0 <= discount <= 100

Apply Discount to Prices LeetCode Solution in Java

class Solution {

    public String discountPrices(String sentence, int discount) {
        String x[] = sentence.split(" ");
        StringBuilder sb = new StringBuilder();
        for (String s : x) {
            if (isPrice(s)) sb.append(calc(Double.parseDouble(s.substring(1)), discount) + " "); 
            else sb.append(s + " ");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    boolean isPrice(String s) {
        return s.startsWith("$") && s.substring(1).matches("\\d+");
    }

    String calc(double num, double discount) {
        double ans = num - (double) ((double) num * discount / 100.00);
        return "$" + String.format("%.2f", ans);
    }
}

Apply Discount to Prices LeetCode Solution in C++

#define ll long long int
#define ld long double
class Solution {
public:
    string check(string s,int d)
    {
        int c=0;
        for(char ch:s)
        {
            if(isdigit(ch))
            {
                c++;
            }
        }
        string res="";
        if(c!=s.length()||c==0)
        return "-1";
        else
        {
            ll zz=stoll(s);
            
            ll dd=(d)*zz;
            
            ld xx=dd/100.0;
            ld rr=zz-xx;
            res=to_string(rr);
            int x=4;
            while(x--)
            res.pop_back();
        
        }
        return res;
    }
    string discountPrices(string s, int d) {
        s+=' ';
        int n=s.length();
        int left=0;
        string ans="";
        for(int i=0;i<n;i++)
        {
            if(s[i]==' ')
            {
                string str=s.substr(left,i-left);
                bool ok=false;
                if(str[0]=='$')
                {
                    string z=str.substr(1);
                    string a=check(z,d);
                    if(a!="-1")
                    {
                      ans+='$';
                      ans+=a;  
                      ans+=' ';
                        ok=true;
                    }
                    else
                    {
                        ans+=str;
                        ans+=' ';
                    }
                }
                else
                {
                    if(!ok)
                    {
                        ans+=str;
                        ans+=' ';
                    }
                }
                left=i+1;
            }
        }
        ans.pop_back();
        return ans;
    }
};

Apply Discount to Prices LeetCode Solution in Python

class Solution:
    def discountPrices(self, sentence: str, discount: int) -> str:
        s = sentence.split() # convert to List to easily update
        m = discount / 100 
        for i,word in enumerate(s):
            if word[0] == "$" and word[1:].isdigit(): # Check whether it is in correct format
                num = int(word[1:]) * (1-m) # discounted price
                w = "$" + "{:.2f}".format(num) #correctly format
                s[i] = w #Change inside the list
        
        return " ".join(s) #Combine the updated list
		```
Apply Discount to Prices LeetCode Solution Review:

In our experience, we suggest you solve this Apply Discount to Prices LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Apply Discount to Prices LeetCode Solution.

Find on LeetCode

Conclusion:

I hope this Apply Discount to Prices LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *