Given an integer and rotates the number of this integer position

Source: Internet
Author: User
Tags integer

[Question:]

Reverse digits of an integer. EXAMPLE1:X = 123, return 321

example2:x = -123, return-321

Solving: Given an integer, the number of this integer is rotated position.

[Analysis:] Here are some good the questions to ask before coding. Bonus points for/If you have already thought through this!

If the digit is 0, what should the output to be? ie, cases such as 10, 100.

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/

Did you notice the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should do you handle such cases?

Throw an exception? Good, but what if throwing a exception is isn't an option? You are would then have to re-design the function (ie, add a extra parameter). Note Point 1: If the last digit of an integer is 0, such as: 10100, then the inversion will turn into 101. NOTE 2: If you enter a number of 1000000003, then the reversal will overflow, you need to pay attention.

[Solution:]

* 
 * Assume the input 123: 
 * 123-> 3   
 *-> + 2   
 * 1-> + 1 *   
 * Public
class Solution {  
    pub LIC int reverse (int x) {  
        int = 0;  
        while (x!= 0) {Results  
            = result * + x% 10;//each time on the basis of the original results to 10 times times larger, plus the remainder  
            x = X/10;  
        Eturn result;  
    }  
     
    public static void Main (string[] args) {  
        Scanner Scanner = new Scanner (new Bufferedinputstream (system.in));  
        while (Scanner.hasnext ()) {  
            int num = Scanner.nextint ();  
            System.out.println (New Solution (). reverse (num));}}  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.