Reverse int within the 32-bit signed integer range: [−2^31, 2^31 − 1]Combining two 32-bit integers into one 64-bit integerDetermine if an int is within rangeLossy packing 32 bit integer to 16 bitComputing the square root of a 64-bit integerKeeping integer addition within boundsSafe multiplication of two 64-bit signed integersLeetcode 10: Regular Expression MatchingSigned integer-to-ascii x86_64 assembler macroReverse the digits of an Integer“Add two numbers given in reverse order from a linked list”

How much character growth crosses the line into breaking the character

What is this called? Old film camera viewer?

Are the IPv6 address space and IPv4 address space completely disjoint?

How to follow the Halacha?

Biological Blimps: Propulsion

250 Floor Tower

Does an advisor owe his/her student anything? Will an advisor keep a PhD student only out of pity?

Pre-modern battle - command it, or fight in it?

What should you do when eye contact makes your subordinate uncomfortable?

How do you make your own symbol when Detexify fails?

Melting point of aspirin, contradicting sources

What is Cash Advance APR?

Symbol used to indicate indivisibility

How do I color the graph in datavisualization?

Pre-mixing cryogenic fuels and using only one fuel tank

Is it safe to use olive oil to clean the ear wax?

Has any country ever had 2 former presidents in jail simultaneously?

Problem with TransformedDistribution

L1 and Ln cache: when are they written?

lightning-datatable row number error

How do you respond to a colleague from another team when they're wrongly expecting that you'll help them?

What does "Scientists rise up against statistical significance" mean? (Comment in Nature)

Are paving bricks differently sized for sand bedding vs mortar bedding?

Is this toilet slogan correct usage of the English language?



Reverse int within the 32-bit signed integer range: [−2^31, 2^31 − 1]


Combining two 32-bit integers into one 64-bit integerDetermine if an int is within rangeLossy packing 32 bit integer to 16 bitComputing the square root of a 64-bit integerKeeping integer addition within boundsSafe multiplication of two 64-bit signed integersLeetcode 10: Regular Expression MatchingSigned integer-to-ascii x86_64 assembler macroReverse the digits of an Integer“Add two numbers given in reverse order from a linked list”













1












$begingroup$


Problem



Reverse digits of a 32-bit signed integer. When the reversed integer overflows return 0.



Feedback



Looking for any ways I can optimize this with modern c++ features overall. I hope my use of const correctness, exception handling, and assertions is implemented well here, please let me know. Is there any way I can use byte operations to reverse the int and keep track of the sign possibly?



Based on the submission feedback from LeetCode, is it safe to say that the time complexity is O(n) and space complexity is O(n)? If I can reduce the complexity in anyway would love to know! Thanks for the feedback in advance.



enter image description here



#include <cassert>
#include <climits>
#include <stdexcept>
#include <string>

class Solution

public:
int reverse(int i)
bool is_signed = false;
if(i < 0) is_signed = true;

auto i_string = std::to_string(i);

std::string reversed = "";
while(!i_string.empty())
reversed.push_back(i_string.back());
i_string.pop_back();


try
i = std::stoi(reversed);
catch (const std::out_of_range& e)
return 0;


if(is_signed) i *= -1;

return i;

;

int main()

Solution s;
assert(s.reverse(1) == 1);
assert(s.reverse(0) == 0);
assert(s.reverse(123) == 321);
assert(s.reverse(120) == 21);
assert(s.reverse(-123) == -321);
assert(s.reverse(1207) == 7021);
assert(s.reverse(INT_MAX) == 0);
assert(s.reverse(INT_MIN) == 0);










share|improve this question











$endgroup$











  • $begingroup$
    This leetcode.com/problems/reverse-integer ?
    $endgroup$
    – Martin R
    5 hours ago










  • $begingroup$
    Yes that's the one
    $endgroup$
    – greg
    4 hours ago















1












$begingroup$


Problem



Reverse digits of a 32-bit signed integer. When the reversed integer overflows return 0.



Feedback



Looking for any ways I can optimize this with modern c++ features overall. I hope my use of const correctness, exception handling, and assertions is implemented well here, please let me know. Is there any way I can use byte operations to reverse the int and keep track of the sign possibly?



Based on the submission feedback from LeetCode, is it safe to say that the time complexity is O(n) and space complexity is O(n)? If I can reduce the complexity in anyway would love to know! Thanks for the feedback in advance.



enter image description here



#include <cassert>
#include <climits>
#include <stdexcept>
#include <string>

class Solution

public:
int reverse(int i)
bool is_signed = false;
if(i < 0) is_signed = true;

auto i_string = std::to_string(i);

std::string reversed = "";
while(!i_string.empty())
reversed.push_back(i_string.back());
i_string.pop_back();


try
i = std::stoi(reversed);
catch (const std::out_of_range& e)
return 0;


if(is_signed) i *= -1;

return i;

;

int main()

Solution s;
assert(s.reverse(1) == 1);
assert(s.reverse(0) == 0);
assert(s.reverse(123) == 321);
assert(s.reverse(120) == 21);
assert(s.reverse(-123) == -321);
assert(s.reverse(1207) == 7021);
assert(s.reverse(INT_MAX) == 0);
assert(s.reverse(INT_MIN) == 0);










share|improve this question











$endgroup$











  • $begingroup$
    This leetcode.com/problems/reverse-integer ?
    $endgroup$
    – Martin R
    5 hours ago










  • $begingroup$
    Yes that's the one
    $endgroup$
    – greg
    4 hours ago













1












1








1





$begingroup$


Problem



Reverse digits of a 32-bit signed integer. When the reversed integer overflows return 0.



Feedback



Looking for any ways I can optimize this with modern c++ features overall. I hope my use of const correctness, exception handling, and assertions is implemented well here, please let me know. Is there any way I can use byte operations to reverse the int and keep track of the sign possibly?



Based on the submission feedback from LeetCode, is it safe to say that the time complexity is O(n) and space complexity is O(n)? If I can reduce the complexity in anyway would love to know! Thanks for the feedback in advance.



enter image description here



#include <cassert>
#include <climits>
#include <stdexcept>
#include <string>

class Solution

public:
int reverse(int i)
bool is_signed = false;
if(i < 0) is_signed = true;

auto i_string = std::to_string(i);

std::string reversed = "";
while(!i_string.empty())
reversed.push_back(i_string.back());
i_string.pop_back();


try
i = std::stoi(reversed);
catch (const std::out_of_range& e)
return 0;


if(is_signed) i *= -1;

return i;

;

int main()

Solution s;
assert(s.reverse(1) == 1);
assert(s.reverse(0) == 0);
assert(s.reverse(123) == 321);
assert(s.reverse(120) == 21);
assert(s.reverse(-123) == -321);
assert(s.reverse(1207) == 7021);
assert(s.reverse(INT_MAX) == 0);
assert(s.reverse(INT_MIN) == 0);










share|improve this question











$endgroup$




Problem



Reverse digits of a 32-bit signed integer. When the reversed integer overflows return 0.



Feedback



Looking for any ways I can optimize this with modern c++ features overall. I hope my use of const correctness, exception handling, and assertions is implemented well here, please let me know. Is there any way I can use byte operations to reverse the int and keep track of the sign possibly?



Based on the submission feedback from LeetCode, is it safe to say that the time complexity is O(n) and space complexity is O(n)? If I can reduce the complexity in anyway would love to know! Thanks for the feedback in advance.



enter image description here



#include <cassert>
#include <climits>
#include <stdexcept>
#include <string>

class Solution

public:
int reverse(int i)
bool is_signed = false;
if(i < 0) is_signed = true;

auto i_string = std::to_string(i);

std::string reversed = "";
while(!i_string.empty())
reversed.push_back(i_string.back());
i_string.pop_back();


try
i = std::stoi(reversed);
catch (const std::out_of_range& e)
return 0;


if(is_signed) i *= -1;

return i;

;

int main()

Solution s;
assert(s.reverse(1) == 1);
assert(s.reverse(0) == 0);
assert(s.reverse(123) == 321);
assert(s.reverse(120) == 21);
assert(s.reverse(-123) == -321);
assert(s.reverse(1207) == 7021);
assert(s.reverse(INT_MAX) == 0);
assert(s.reverse(INT_MIN) == 0);







c++ c++11 interview-questions integer






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 5 hours ago









Martin R

16.2k12366




16.2k12366










asked 5 hours ago









greggreg

37018




37018











  • $begingroup$
    This leetcode.com/problems/reverse-integer ?
    $endgroup$
    – Martin R
    5 hours ago










  • $begingroup$
    Yes that's the one
    $endgroup$
    – greg
    4 hours ago
















  • $begingroup$
    This leetcode.com/problems/reverse-integer ?
    $endgroup$
    – Martin R
    5 hours ago










  • $begingroup$
    Yes that's the one
    $endgroup$
    – greg
    4 hours ago















$begingroup$
This leetcode.com/problems/reverse-integer ?
$endgroup$
– Martin R
5 hours ago




$begingroup$
This leetcode.com/problems/reverse-integer ?
$endgroup$
– Martin R
5 hours ago












$begingroup$
Yes that's the one
$endgroup$
– greg
4 hours ago




$begingroup$
Yes that's the one
$endgroup$
– greg
4 hours ago










1 Answer
1






active

oldest

votes


















3












$begingroup$

General comments



  • There is no reason to use a class. Instead, the functionality should be made into a free function.


  • Your code is overly complicated. There is no reason to make new string from which you erase characters one-by-one. Instead, you can convert the input integer to a string and use a standard function to reverse that.


  • Also, pay attention to const correctness. This protects from unintended mistakes and helps the compiler optimize more.


I would simplify your function to just:



int reverse(int i) 

try

auto reversed std::to_string(i) ;
std::reverse(reversed.begin(), reversed.end());

const auto result std::stoi(reversed) ;
return i < 0 ? -1 * result : result;

catch (const std::out_of_range& e)

return 0;




Further comments




  • If you want to have a fast solution, you should avoid std::string altogether. This you can do by "iterating" through the digits using arithmetic operations (division and modulus), as in (using std::string to only show you what is happening):



    int x = 1234;
    std::string s;

    while (x > 0)

    s.push_back('0' + (x % 10));
    x /= 10;


    std::cout << s << "n"; // Prints 4321


    I will let you take it from here to use these ideas to make your program even faster.



  • Regarding your theoretical question concerning complexity, if we assume that the input is treated as a string of n characters, there is Omega(n) lower bound by a trivial adversary argument. Basically, if you don't spend at least n time, you can't read the whole of the input, and then you cannot guarantee correct output on every instance.






share|improve this answer











$endgroup$












    Your Answer





    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216068%2freverse-int-within-the-32-bit-signed-integer-range-%25e2%2588%2592231-231-%25e2%2588%2592-1%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3












    $begingroup$

    General comments



    • There is no reason to use a class. Instead, the functionality should be made into a free function.


    • Your code is overly complicated. There is no reason to make new string from which you erase characters one-by-one. Instead, you can convert the input integer to a string and use a standard function to reverse that.


    • Also, pay attention to const correctness. This protects from unintended mistakes and helps the compiler optimize more.


    I would simplify your function to just:



    int reverse(int i) 

    try

    auto reversed std::to_string(i) ;
    std::reverse(reversed.begin(), reversed.end());

    const auto result std::stoi(reversed) ;
    return i < 0 ? -1 * result : result;

    catch (const std::out_of_range& e)

    return 0;




    Further comments




    • If you want to have a fast solution, you should avoid std::string altogether. This you can do by "iterating" through the digits using arithmetic operations (division and modulus), as in (using std::string to only show you what is happening):



      int x = 1234;
      std::string s;

      while (x > 0)

      s.push_back('0' + (x % 10));
      x /= 10;


      std::cout << s << "n"; // Prints 4321


      I will let you take it from here to use these ideas to make your program even faster.



    • Regarding your theoretical question concerning complexity, if we assume that the input is treated as a string of n characters, there is Omega(n) lower bound by a trivial adversary argument. Basically, if you don't spend at least n time, you can't read the whole of the input, and then you cannot guarantee correct output on every instance.






    share|improve this answer











    $endgroup$

















      3












      $begingroup$

      General comments



      • There is no reason to use a class. Instead, the functionality should be made into a free function.


      • Your code is overly complicated. There is no reason to make new string from which you erase characters one-by-one. Instead, you can convert the input integer to a string and use a standard function to reverse that.


      • Also, pay attention to const correctness. This protects from unintended mistakes and helps the compiler optimize more.


      I would simplify your function to just:



      int reverse(int i) 

      try

      auto reversed std::to_string(i) ;
      std::reverse(reversed.begin(), reversed.end());

      const auto result std::stoi(reversed) ;
      return i < 0 ? -1 * result : result;

      catch (const std::out_of_range& e)

      return 0;




      Further comments




      • If you want to have a fast solution, you should avoid std::string altogether. This you can do by "iterating" through the digits using arithmetic operations (division and modulus), as in (using std::string to only show you what is happening):



        int x = 1234;
        std::string s;

        while (x > 0)

        s.push_back('0' + (x % 10));
        x /= 10;


        std::cout << s << "n"; // Prints 4321


        I will let you take it from here to use these ideas to make your program even faster.



      • Regarding your theoretical question concerning complexity, if we assume that the input is treated as a string of n characters, there is Omega(n) lower bound by a trivial adversary argument. Basically, if you don't spend at least n time, you can't read the whole of the input, and then you cannot guarantee correct output on every instance.






      share|improve this answer











      $endgroup$















        3












        3








        3





        $begingroup$

        General comments



        • There is no reason to use a class. Instead, the functionality should be made into a free function.


        • Your code is overly complicated. There is no reason to make new string from which you erase characters one-by-one. Instead, you can convert the input integer to a string and use a standard function to reverse that.


        • Also, pay attention to const correctness. This protects from unintended mistakes and helps the compiler optimize more.


        I would simplify your function to just:



        int reverse(int i) 

        try

        auto reversed std::to_string(i) ;
        std::reverse(reversed.begin(), reversed.end());

        const auto result std::stoi(reversed) ;
        return i < 0 ? -1 * result : result;

        catch (const std::out_of_range& e)

        return 0;




        Further comments




        • If you want to have a fast solution, you should avoid std::string altogether. This you can do by "iterating" through the digits using arithmetic operations (division and modulus), as in (using std::string to only show you what is happening):



          int x = 1234;
          std::string s;

          while (x > 0)

          s.push_back('0' + (x % 10));
          x /= 10;


          std::cout << s << "n"; // Prints 4321


          I will let you take it from here to use these ideas to make your program even faster.



        • Regarding your theoretical question concerning complexity, if we assume that the input is treated as a string of n characters, there is Omega(n) lower bound by a trivial adversary argument. Basically, if you don't spend at least n time, you can't read the whole of the input, and then you cannot guarantee correct output on every instance.






        share|improve this answer











        $endgroup$



        General comments



        • There is no reason to use a class. Instead, the functionality should be made into a free function.


        • Your code is overly complicated. There is no reason to make new string from which you erase characters one-by-one. Instead, you can convert the input integer to a string and use a standard function to reverse that.


        • Also, pay attention to const correctness. This protects from unintended mistakes and helps the compiler optimize more.


        I would simplify your function to just:



        int reverse(int i) 

        try

        auto reversed std::to_string(i) ;
        std::reverse(reversed.begin(), reversed.end());

        const auto result std::stoi(reversed) ;
        return i < 0 ? -1 * result : result;

        catch (const std::out_of_range& e)

        return 0;




        Further comments




        • If you want to have a fast solution, you should avoid std::string altogether. This you can do by "iterating" through the digits using arithmetic operations (division and modulus), as in (using std::string to only show you what is happening):



          int x = 1234;
          std::string s;

          while (x > 0)

          s.push_back('0' + (x % 10));
          x /= 10;


          std::cout << s << "n"; // Prints 4321


          I will let you take it from here to use these ideas to make your program even faster.



        • Regarding your theoretical question concerning complexity, if we assume that the input is treated as a string of n characters, there is Omega(n) lower bound by a trivial adversary argument. Basically, if you don't spend at least n time, you can't read the whole of the input, and then you cannot guarantee correct output on every instance.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 4 hours ago

























        answered 4 hours ago









        JuhoJuho

        1,471612




        1,471612



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216068%2freverse-int-within-the-32-bit-signed-integer-range-%25e2%2588%2592231-231-%25e2%2588%2592-1%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Are there any comparative studies done between Ashtavakra Gita and Buddhim?How is it wrong to believe that a self exists, or that it doesn't?Can you criticise or improve Ven. Bodhi's description of MahayanaWas the doctrine of 'Anatta', accepted as doctrine by modern Buddhism, actually taught by the Buddha?Relationship between Buddhism, Hinduism and Yoga?Comparison of Nirvana, Tao and Brahman/AtmaIs there a distinction between “ego identity” and “craving/hating”?Are there many differences between Taoism and Buddhism?Loss of “faith” in buddhismSimilarity between creation in Abrahamic religions and beginning of life in Earth mentioned Agganna Sutta?Are there studies about the difference between meditating in the morning versus in the evening?Can one follow Hinduism and Buddhism at the same time?Are there any prohibitions on participating in other religion's practices?Psychology of 'flow'

            fallocate: fallocate failed: Text file busy in Ubuntu 17.04? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)defragmenting and increasing performance of old lubuntu system with swap partitionIssue with increasing the root partition from the swapthis /usr/bin/dpkg returned error || ubuntu-16.04, 64bitDefault 17.04 swap file locationHow to Resize Ubuntu 17.04 Zesty Swap file size?Ubuntu freezes from online formsMy Laptop is not starting after upgrade ubuntu 16.04 (Kernel 4.8.0-38 to 04.10.0-36)hcp: ERROR: FALLOCATE FAILED!Not sure my swap is being usedWine 3.0 asking for more virtual free swap

            Where is the suspend/hibernate button in GNOME Shell? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)No suspend option in UI on Bionic BeaverHow can I set sleep mode in ubuntu18.04 LTS and what is the short cut key to do so?17.10 suspend not availableUbuntu 18.04 LTS missing sleep optionUbuntu 18.04 LTS - missing suspend option when power button is pressedHow to put Thinkpad X1 Extreme to sleep in Ubuntu 18.10?Suspend Button in interactive power button menu18.04 - Keep programs running after logging outway to disable Hibernate from within gconf-editor so button disappears?How can I hibernate from GNOME Shell?How can I hibernate/suspend from the command line and do so at a specific timeNo permission to suspend/hibernate after upgrading to 12.10MATE - Missing Suspend and Hibernate buttons, pressing power button shutdowns system immediatelyUbuntu 14.04: Suspend, Hibernate and Suspend-hybrid in the menu?Change “power-button-action” comand for “hibernate” option in GNOME 3.18Shutdown / Power off button does always go to suspend on 17.10Hibernate after suspend stopped working in 17.10Why doesn't the keyboard screenshot button work on Ubuntu with GNOME shell?