C++ || 2 approaches || std::to_chars and handrolled
-\nTitle: C++ || 2 approaches || std::to_chars and handrolled\nProblem: 504\nURL: https://leetcode.com/problems/base-7/discuss/221488/c-3-liner-using-stdto_char
<!---\nTitle: C++ || 2 approaches || std::to_chars and handrolled\nProblem: 504\nURL: https://leetcode.com/problems/base-7/discuss/221488/c-3-liner-using-stdto_chars\n-->\n\n# Approach 1: std::to_chars\n\n```cpp\n    static std::string convertToBase7(int num) {\n        std::array<char, sizeof(int) * 4> buf = {0};\n        std::to_chars(buf.begin(), buf.end(), num, 7);\n        return std::string(buf.data());\n    }\n```\n\n# Approach 2: handrolled\n\n```cpp\n    static string convertToBase7(int num) {\n        if (num < 0) return "-" + convertToBase7(-num);\n        \n        if (num == 0) return "0";\n\n        string ans;\n        while (num) {\n            ans.push_back(num % 7 + \'0\');\n            num /= 7;\n        }\n        reverse(ans.begin(), ans.end());\n        return ans;\n    }\n```\n\n_As always: Feedback, questions, and comments are welcome. Leaving an upvote sparks  joy! :)_\n\n**p.s. Join us on the [LeetCode The Hard Way Discord Server](https://discord.gg/hFUyVyWy2E)!**\n
['C']