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 could a planet have erratic days?

Closed-form expression for certain product

lightning-datatable row number error

C++ debug of nlohmann json using GDB

What does chmod -u do?

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

A social experiment. What is the worst that can happen?

Count the occurrence of each unique word in the file

How do I color the graph in datavisualization?

250 Floor Tower

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

Not using 's' for he/she/it

Why can Carol Danvers change her suit colours in the first place?

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

Rising and falling intonation

If infinitesimal transformations commute why dont the generators of the Lorentz group commute?

Why is so much work done on numerical verification of the Riemann Hypothesis?

How did Rebekah know that Esau was planning to kill his brother in Genesis 27:42?

Freedom of speech and where it applies

What was this official D&D 3.5e Lovecraft-flavored rulebook?

Non-trope happy ending?

Does a 'pending' US visa application constitute a denial?

What if a revenant (monster) gains fire resistance?

On a tidally locked planet, would time be quantized?



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
    3 hours ago










  • $begingroup$
    Yes that's the one
    $endgroup$
    – greg
    3 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
    3 hours ago










  • $begingroup$
    Yes that's the one
    $endgroup$
    – greg
    3 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 3 hours ago









Martin R

16.2k12366




16.2k12366










asked 3 hours ago









greggreg

37018




37018











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










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
















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










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















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




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












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




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










1 Answer
1






active

oldest

votes


















2












$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









    2












    $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$

















      2












      $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$















        2












        2








        2





        $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 2 hours ago

























        answered 3 hours ago









        JuhoJuho

        1,461612




        1,461612



























            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

            Era Viking Índice Início da Era Viquingue | Cotidiano | Sociedade | Língua | Religião | A arte | As primeiras cidades | As viagens dos viquingues | Viquingues do Oeste e Leste | Fim da Era Viquingue | Fontes históricas | Referências Bibliografia | Ligações externas | Menu de navegação«Sverige då!»«Handel I vikingetid»«O que é Nórdico Antigo»Mito, magia e religião na volsunga saga Um olhar sobre a trajetória mítica do herói sigurd«Bonden var den verklige vikingen»«Vikingatiden»«Vikingatiden»«Vinland»«Guerreiras de Óðinn: As Valkyrjor na Mitologia Viking»1519-9053«Esculpindo símbolos e seres: A arte viking em pedras rúnicas»1679-9313Historia - Tema: VikingarnaAventura e Magia no Mundo das Sagas IslandesasEra Vikinge

            What's the metal clinking sound at the end of credits in Avengers: Endgame?What makes Thanos so strong in Avengers: Endgame?Who is the character that appears at the end of Endgame?What happens to Mjolnir (Thor's hammer) at the end of Endgame?The People's Ages in Avengers: EndgameWhat did Nebula do in Avengers: Endgame?Messing with time in the Avengers: Endgame climaxAvengers: Endgame timelineWhat are the time-travel rules in Avengers Endgame?Why use this song in Avengers: Endgame Opening Logo Sequence?Peggy's age in Avengers Endgame

            Mortes em março de 2019 Referências Menu de navegação«Zhores Alferov, Nobel de Física bielorrusso, morre aos 88 anos - Ciência»«Fallece Rafael Torija, o bispo emérito de Ciudad Real»«Peter Hurford dies at 88»«Keith Flint, vocalista do The Prodigy, morre aos 49 anos»«Luke Perry, ator de 'Barrados no baile' e 'Riverdale', morre aos 52 anos»«Former Rangers and Scotland captain Eric Caldow dies, aged 84»«Morreu, aos 61 anos, a antiga lenda do wrestling King Kong Bundy»«Fallece el actor y director teatral Abraham Stavans»«In Memoriam Guillaume Faye»«Sidney Sheinberg, a Force Behind Universal and Spielberg, Is Dead at 84»«Carmine Persico, Colombo Crime Family Boss, Is Dead at 85»«Dirigent Michael Gielen gestorben»«Ciclista tricampeã mundial e prata na Rio 2016 é encontrada morta em casa aos 23 anos»«Pagan Community Notes: Raven Grimassi dies, Indianapolis pop-up event cancelled, Circle Sanctuary announces new podcast, and more!»«Hal Blaine, Wrecking Crew Drummer, Dies at 90»«Morre Coutinho, que editou dupla lendária com Pelé no Santos»«Cantor Demétrius, ídolo da Jovem Guarda, morre em SP»«Ex-presidente do Vasco, Eurico Miranda morre no Rio de Janeiro»«Bronze no Mundial de basquete de 1971, Laís Elena morre aos 76 anos»«Diretor de Corridas da F1, Charlie Whiting morre aos 66 anos às vésperas do GP da Austrália»«Morreu o cardeal Danneels, da Bélgica»«Morreu o cartoonista Augusto Cid»«Morreu a atriz Maria Isabel de Lizandra, de "Vale Tudo" e novelas da Tupi»«WS Merwin, prize-winning poet of nature, dies at 91»«Atriz Márcia Real morre em São Paulo aos 88 anos»«Mauritanie: décès de l'ancien président Mohamed Mahmoud ould Louly»«Morreu Dick Dale, o rei da surf guitar e de "Pulp Fiction"»«Falleció Víctor Genes»«João Carlos Marinho, autor de 'O Gênio do Crime', morre em SP»«Legendary Horror Director and SFX Artist John Carl Buechler Dies at 66»«Morre em Salvador a religiosa Makota Valdina»«مرگ بازیکن‌ سابق نساجی بر اثر سقوط سنگ در مازندران»«Domingos Oliveira morre no Rio»«Morre Airton Ravagniani, ex-São Paulo, Fla, Vasco, Grêmio e Sport - Notícias»«Morre o escritor Flavio Moreira da Costa»«Larry Cohen, Writer-Director of 'It's Alive' and 'Hell Up in Harlem,' Dies at 77»«Scott Walker, experimental singer-songwriter, dead at 76»«Joseph Pilato, Day of the Dead Star and Horror Favorite, Dies at 70»«Sheffield United set to pay tribute to legendary goalkeeper Ted Burgin who has died at 91»«Morre Rafael Henzel, sobrevivente de acidente aéreo da Chapecoense»«Morre Valery Bykovsky, um dos primeiros cosmonautas da União Soviética»«Agnès Varda, cineasta da Nouvelle Vague, morre aos 90 anos»«Agnès Varda, cineasta francesa, morre aos 90 anos»«Tania Mallet, James Bond Actress and Helen Mirren's Cousin, Dies at 77»e