{"id":2065,"date":"2024-03-03T15:00:00","date_gmt":"2024-03-03T15:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=2065"},"modified":"2024-03-04T07:44:44","modified_gmt":"2024-03-04T07:44:44","slug":"reverse-integer-problem","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/reverse-integer-problem\/","title":{"rendered":"Reverse Integer Problem Solved (C++, Java, Python)"},"content":{"rendered":"\n<p>Reverse a string is a common question that can be solved through inbuilt functions like a reverse in C++ and Java. The basic idea to solve this type of question is to start your loop from the back and keep storing the values in the new string, but how to do with numbers? In this article, we will try to solve the Reverse Integer Problem.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is the Reverse Integer problem?<\/strong><\/h2>\n\n\n\n<p><strong>In the Reverse Integer problem, you are given an integer that can lie from [-(2^31), (2^31 &#8211; 1)]. You have to reverse its digits and return this new number. If the new integer does not lie between [-(2^31), (2^31 &#8211; 1)] return 0.<\/strong><\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n\n<p><strong>Input<\/strong>: -213<\/p>\n\n\n\n<p><strong>Output<\/strong>: -312<\/p>\n\n\n\n<p><strong>Explanation<\/strong>: After reversing 213 we got 312 but as the input is negative return -312<\/p>\n\n\n\n<p>Take this another example:<\/p>\n\n\n\n<p><strong>Input<\/strong>: 1534236469<\/p>\n\n\n\n<p><strong>Output <\/strong>: 0<\/p>\n\n\n\n<p><strong>Explanation<\/strong>: After reversing the digits we got 9646324351 which is greater than (2^31)-1 so we return 0.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/Z-HJDFOqYcLDwTfkJJUS0GRP6ZcVFEYuofIDPYsCtFS1KslgKMsIhBoO5G1vbwRFOBIsWhvZmwjBEP5tqegJhpVv8jkCg0zVqflooaR9UH31D7U8GKXN_oZqZm6cDSme27Rc_VB0Jqo1Xl17hP_KLgE\" alt=\"Example of Reverse Interger problem\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Brute Force Approach<\/strong><\/h2>\n\n\n\n<p>The basic approach is to store all the digits of the given integer into an array and after that reverse that array and make a new integer out of it. Here is the process:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>First, create a vector.<\/li>\n\n\n\n<li>Now start pushing the integers into the array by finding the remainder of the given integer with 10, the remainder is the last number. Push this number and divide the given integer by 10.<\/li>\n\n\n\n<li>Keep on adding the numbers into the array till the integer becomes 0.<\/li>\n\n\n\n<li>Now create a long variable result that will give the result. Assign the result with 0.<\/li>\n\n\n\n<li>Start iterating the array and keep on adding this new number at present at the particular index of the array (<strong> result = (result*10) + arr[i] ).<\/strong><\/li>\n\n\n\n<li>If the given integer is negative make result = &#8211; result.<\/li>\n\n\n\n<li>Return this new result if it lies in the range otherwise return 0.\u00a0<\/li>\n<\/ol>\n\n\n\n<p>The time complexity for the above approach is O(32) ~ O(1). As we keep on dividing the given integer by 10. And maximum number of digits a number can have is 31 as our value lies between [-(2^31), (2^31 &#8211; 1)]. The space complexity for the above code is O(31) as we are storing our digits in an array.\u00a0<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Inbuilt Function Approach<\/strong><\/h2>\n\n\n\n<p><strong>Another way to reverse an integer is to first convert the given integer into a string and then reverse that string through an inbuilt reverse string function.<\/strong> Once the string is reversed again convert the string into the integer. Check if the resultant integer lies in between the range or not. If it does not lie between the range return 0. Otherwise, return the integer.<\/p>\n\n\n\n<p>Let\u2019s examine step by step approach:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Create a string s.&nbsp;<\/li>\n\n\n\n<li>Create a boolean variable flag that checks if the given integer is less than 0 or not.<\/li>\n\n\n\n<li>Now if the integer is negative make it positive.<\/li>\n\n\n\n<li>Change the integer to the string and store it in the string s.<\/li>\n\n\n\n<li>Reverse the string s.<\/li>\n\n\n\n<li>Store this string into an integer by converting it into an integer.<\/li>\n\n\n\n<li>Check if the flag is true or not. If true make the new integer -ve.<\/li>\n\n\n\n<li>Check if the integer lies between the range or not if not return 0. Otherwise, return that integer.<\/li>\n<\/ol>\n\n\n\n<p>The time complexity for the above code is O(32) as we are using the inbuilt function reverse whose time complexity is O(n) where n is the size of the string. As in our case the size will never be more than 32 so the time complexity is O(32). The space complexity for the above code is O(32) as we are using a reverse function which took O(n) space complexity.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Optimized Approach<\/strong><\/h2>\n\n\n\n<p>This approach is the same as the brute force approach. Inside of storing the values in the array we are directly updating our resultant array. Because of this, our space complexity will be reduced from O(32) to O(1).&nbsp;<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/8Cqvn9L-K99lesvBtKXs6oB6XPLeQUIPNSqBVBp8P_kGswrdm1AC-ivce1eh-Hr6wHZxFCa3wX5QEyPdkF7aLjdgRzMZ39GDbPWUarvrgzoMcO5hkALdUgrUYhEhuy6IuwfLlpW47-GKNDp_qz3Q60c\" alt=\"Given integer\"\/><\/figure>\n\n\n\n<ol class=\"wp-block-list\">\n<li>First, create a long variable result and a boolean variable flag.<\/li>\n\n\n\n<li>Check if the integer is negative or not if it is negative make the flag value true.<\/li>\n\n\n\n<li>Now keep on adding the remainder of the integer till the integer becomes 0. The result will be <strong>( result&nbsp; = (result*10) + (num%10))<\/strong>. And make (<strong>num = num\/10<\/strong>).<\/li>\n\n\n\n<li>Now check if the flag is true and make result = &#8211; result.<\/li>\n\n\n\n<li>Return the result if it lies between the range otherwise return 0.<\/li>\n<\/ol>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/sRyfNGMz2b7wmZ7-P_97NC24o0he-wNWnVbKB1skmjz7zUdO2fi6V-RXFDhESsYRTUZI3Ohw_N00RWCSjnOm6dUJi6dg2Y0O59xs-gZ0j2cELN5E-eTlBfDOnQHNgLT_UEeShf_75zIK62L9K_LiewA\" alt=\"Result\"\/><\/figure>\n\n\n\n<p>Let\u2019s examine how we can implement it:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Here is the C++ program to solve the Reverse Integer problem:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include&lt;bits\/stdc++.h&gt;\nusing namespace std;\n\nint main(){\n    long long int num = -241;\n\n    bool flag = false;\n    if(num &lt; 0) {\n        flag = true;\n        num = -num;\n    }\n    long long int result = 0;\n\n    while(num&gt;0){\n        result = (result*10) + (num%10);\n        num = num\/10;\n    }\n\n    if(flag) result = - result;\n\n    if((result &gt; INT_MAX) || (result &lt; INT_MIN)) {\n        cout&lt;&lt;0&lt;&lt;endl;\n        return 0;\n    }\n\n    \/\/ result  = -142\n    cout&lt;&lt;result&lt;&lt;endl;\n    \n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>Below is how to code it with Java:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">class ReverseInteger {\n    public static void main(String[] args) {\n        long num = -241;\n\n        boolean flag = false;\n        if (num &lt; 0) {\n            flag = true;\n            num = -num;\n        }\n        long result = 0;\n\n        while (num &gt; 0) {\n            result = (result * 10) + (num % 10);\n            num = num \/ 10;\n        }\n\n        if (flag) result = -result;\n\n        if (result &gt; Integer.MAX_VALUE || result &lt; Integer.MIN_VALUE) {\n            System.out.println(0);\n            return;\n        }\n\n        \/\/ result  = -142\n        System.out.println(result);\n    }\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>You can do the same with Python also:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">num = -241\n\nflag = False\nif num &lt; 0:\n    flag = True\n    num = -num\nresult = 0\n\nwhile num &gt; 0:\n    result = (result * 10) + (num % 10)\n    num = num \/\/ 10\n\nif flag:\n    result = -result\n\nif result &gt; 2**31 - 1 or result &lt; -2**31:\n    print(0)\nelse:\n    # result  = -142\n    print(result)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-0486a615a7eef72741c02f24799adbc8\" style=\"background-color:#fedcba\"><code>-142<\/code><\/pre>\n\n\n\n<p>The time complexity for the above code is O(1). As we are just iterating over the integer whose maximum size is 31 so time complexity will be O(32) ~ O(1). The space complexity is also reduced to O(1).<\/p>\n\n\n\n<p>Let&#8217;s compare all the approaches to solve the Reverse Integer problem in the end:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th><strong>Approach<\/strong><\/th><th class=\"has-text-align-center\" data-align=\"center\"><strong> Time Complexity<\/strong><\/th><th class=\"has-text-align-center\" data-align=\"center\"><strong>Space Complexity<\/strong><\/th><th><strong>Descriptions<\/strong><\/th><\/tr><\/thead><tbody><tr><td>Brute Force<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(1)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(32)<\/td><td>We are using an array to store the digits of the given integer.<\/td><\/tr><tr><td>Inbuilt Function<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(32) ~ O(1)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(32)<\/td><td>We are using the inbuilt function string to int, int to string, and reverse string functions.<\/td><\/tr><tr><td>Optimized&nbsp;<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(1)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(1)<\/td><td>In this, we are using the same approach as we used in brute force. Instead of storing values into an array we are updating are resultant variable.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this article, we discussed the Reverse Integer problem from <a href=\"https:\/\/leetcode.com\/problems\/reverse-integer\/description\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">leetcode<\/a>. The base case is to check if the number lies between the given range or not. Also, we have to take care of using long variables to store the reverse integer as the integer might overflow which leads to run time error. You can check more <a href=\"https:\/\/favtutor.com\/articles\/category\/data-structures-algorithms\/\">programming DSA problems here<\/a> to practice more.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Understand how to solve the Reverse Integer Problem from leetcode using implementation in C++, Java, and Python.<\/p>\n","protected":false},"author":14,"featured_media":2067,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-2065","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2065","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=2065"}],"version-history":[{"count":3,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2065\/revisions"}],"predecessor-version":[{"id":2138,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2065\/revisions\/2138"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/2067"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=2065"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=2065"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=2065"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}