Concise readable C++ solution
\n    string countOfAtoms(string formula, int i =0) {  \n       string ans;\n       auto m= decode(formula, i);\n        for(auto e :m) ans+=e.first+ (e.second=
```\n    string countOfAtoms(string formula, int i =0) {  \n       string ans;\n       auto m= decode(formula, i);\n        for(auto e :m) ans+=e.first+ (e.second==1? "":to_string(e.second));     \n        return ans;\n        \n    }\n    \n    map<string, int> decode(string& s, int& i) {\n        string ans;\n        int n =s.size();\n        \n        auto getNum =[&] (int& i){\n            int cnt=0;\n            while(i<n && isdigit(s[i])) cnt = cnt*10 + s[i++]-\'0\';\n            return max(cnt,1);\n        };\n        auto getElement =[&] (int& i){\n             string elem;\n            if(i<n &&isupper(s[i]))  elem+=s[i++];            \n            while(i<n && islower(s[i]))elem+=s[i++];\n            return elem;\n        };\n\n         map<string, int> m;\n         while (i < n && s[i] != \')\'){              \n             string element = getElement(i); \n             if(!element.empty())m[element] +=getNum(i);\n             if(s[i]==\'(\'){\n                 i++;\n                 auto m1=decode(s,i);\n                 i++; \n                 int cnt =getNum(i);\n                 for(auto e :m1)  m[e.first]+=e.second*cnt;\n             }\n            }\n   \n        return m; \n         \n         \n     }\n```
[]