samedi 29 octobre 2022

43. Multiply String

Its working for all random testcases and 153/300 testcases however it isnt working for some of the testcases , it will be really helpful if someone can find the mistake.

`

class Solution {
public:
    
    int stringtoint(string str){
       int size = str.size()-1;
       long long int num = 0;
        
        unordered_map<char,int>umap;
            umap.insert(pair<char,int>('0',0));
            umap.insert(pair<char,int>('1',1));
            umap.insert(pair<char,int>('2',2));
            umap.insert(pair<char,int>('3',3));
            umap.insert(pair<char,int>('4',4));
            umap.insert(pair<char,int>('5',5));
            umap.insert(pair<char,int>('6',6));
            umap.insert(pair<char,int>('7',7));
            umap.insert(pair<char,int>('8',8));
            umap.insert(pair<char,int>('9',9));
        
        for(int i = 0 ; i < str.size() ; i++){
            if(umap.find(str[i])!=umap.end())
                num = num + umap[str[i]]*pow(10,size);
            
            size--;
        }
        
        return num;
        
    }
    
    string multiply(string num1, string num2) {
        
        
        string sol = "0";
        
        long long int n1 = stringtoint(num1);
        long long int n2 = stringtoint(num2);
        long long int prod = n1*n2;
        
        
        if(prod==0)
            return sol;
        
        string ans = "";
        
        unordered_map<int,string>umap;
        umap[0] = '0';
        umap[1]= '1';
        umap[2]= '2';
        umap[3]= '3';
        umap[4]= '4';
        umap[5]= '5';
        umap[6]= '6';
        umap[7]= '7';
        umap[8]= '8';
        umap[9]= '9';
        
            
        
            while(prod!=0){
                int digit = prod%10;
                if(umap.find(digit)!=umap.end()){
                    ans = ans + umap[digit];
                }
                prod = prod/10;    
            }
        
        reverse(ans.begin() , ans.end());
        
        return ans;
        
    }
};

`

I tried to first convert string to numbers using a map and then simpy multiply those two numbers and thn simply map that product to a string again using a map.




Aucun commentaire:

Enregistrer un commentaire