Thousand Separator

Question, given an integer & you have to add thousand separator & return it as string. First we will store given number in string format (in this way it will be reversed). Now after every 3 digit we will add '.' & at last display the string.


class Solution {
public:
    string thousandSeparator(int n) {
        int c=0, i;
        string s = "", ss = "";
        
        if(n==0)
        {
          ss = (char)(n + '0');  
          return ss; 
        }
            
        while(n>0)
        {
          s += (char)(n%10 + '0');
          n /= 10;
        }
        for(i = 0; i<s.length(); i++)
        {
          if(c==3){ ss = '.' + ss; c = 0; }
          ss = s[i] + ss;
          c++;  
        }
        return ss;
    }
};

 

Related Posts : Must do questions of LeetCode, Must do questions for Competitive coding

No comments:

If you have any doubt or suggestion let me know in comment section.

Powered by Blogger.