【模板总结】整数反转

7. 整数反转

   public int reverse(int x) {
      int ans = 0;
      while(x != 0){
         if((ans < Integer.MIN_VALUE / 10) || (ans > Integer.MAX_VALUE / 10)){
            return 0;
         }
         int num = x % 10;
         ans = ans * 10 + num;
         x /= 10;
      }
      return ans;
   }

8. 字符串转换整数 (atoi)

   public int myAtoi(String s) {
      String s1 = s.trim();
      char[] str = s1.toCharArray();
      if(str == null || str.length == 0){
         return 0;
      }
      int flag = 1;
      int index = 0;
      if(str[index] == '-'){
         flag = -flag;
         index++;
      }else if(str[index] == '+'){
         index++;
      }
      int ans = 0;
      while(index < str.length){
         if(str[index] > '9' || str[index] < '0'){
            break;
         }
         if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && str[index] - '0' > Integer.MAX_VALUE % 10)) {
            return Integer.MAX_VALUE;
         }
         if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && str[index] - '0' > -(Integer.MIN_VALUE % 10))) {   
            return Integer.MIN_VALUE;
         }
         ans = ans * 10 + flag * (str[index] - '0');
         index++;
      }
      return ans;
   }

9. 回文数

在这里插入图片描述

   public boolean isPalindrome(int x) {
      int begin = x;
      if(x < 0){
         return false;
      }
      int ans = 0;
      while(x != 0){
         if(ans < Integer.MIN_VALUE /10 || ans > Integer.MAX_VALUE / 10){
            return false;
         }
         int num = x % 10;
         ans = ans * 10 + num;
         x /= 10;
      }
      return ans == begin;
   }

31. 下一个排列

在这里插入图片描述

   public void nextPermutation(int[] nums) {
      int N = nums.length;
      for (int i = N - 1; i >= 1; i--) {

         if(nums[i] > nums[i - 1]){
            for (int j = N - 1; j >= i; j--) {
                if(nums[j] > nums[i - 1]){
                   int a = nums[i - 1];
                   nums[i - 1] = nums[j];
                   nums[j] = a;
                   break;
                }
            }
            Arrays.sort(nums, i, N);
            return;
         }
         
      }
      Arrays.sort(nums);
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值