This is the first article I participated in beginners’ introduction

1. Title Description


Integer inversion

To give you one32A signed integer x of bits that returns the result of reversing the numeric portion of x. If the integer after inversion exceeds32The range of signed integers of bits [−231.231 − 1] and return0. Suppose the environment does not allow storage64Bit integer (signed or unsigned).Copy the code
  • From simple to difficult, step by step, come on!

Second, train of thought analysis


  • Look at the example, understand the topic, clear thinking, and then write code to achieve!

  • Example 1:

    Enter: x =123Output:321
    Copy the code
  • Example 2:

    Enter: x = -123Output: -321
    Copy the code
  • Example 3:

    Enter: x =120Output:21
    Copy the code
  • Example 4:

    Enter: x =0Output:0
    Copy the code
  • Tip:

  • Analysis of ideas:
    • Note that this prompt tells us that the inverted value should be between -2147483648 and 2147483647

    • So let’s do positive and negative numbers

      • Returns 0 if the number is 0
      • If the value is positive, determine whether overflow, overflow returns 0, otherwise calculate
      • If the value is negative, check whether overflow, overflow returns 0, otherwise calculate
    • If the mod is greater than 7, it’s out of bounds and returns 0

    • Otherwise, the normal calculation returns

AC code


  • Solve the problem according to the train of thought

    public static int reverse(int x) {
          / / - between 2147483648 and 2147483647
          int res = 0;
          int digit;
    
          while(x ! =0) {if(res > 214748364) {return 0;
              }
              if(res == 214748364){
                  res = res * 10;
                  digit = x % 10;
                  if(digit > 7) {return 0;
                  }
                  else{
                      res = res + digit;
                      returnres; }}/ / negative
              if(res < -214748364) {return 0;
              }
              if(res == -214748364){
                  res = res * 10;
                  digit = x % 10;
                  if(digit < -8) {return 0;
                  }
                  else{
                      res = res + digit;
                      return res;
                  }
              }
              res = res * 10;
              digit = x % 10;
              res = res + digit;
              x = x / 10;
          }
          return res;
      }
    Copy the code

Four,

  • Wow,, write out this problem I also feel quite easy, and then looked at other people’s solution. It was a stupid way to break the defense.

  • Quality problem solving recommended

    • The official answer key
    • Big guy uses stack to solve