算法

LeetCode7.整数反转

2021-07-11  本文已影响0人  Timmy_zzh
1.题目描述
示例 1:
输入:x = 123
输出:321

示例 2:
输入:x = -123
输出:-321

示例 3:
输入:x = 120
输出:21

示例 4:
输入:x = 0
输出:0
2.解题思路
public int reverse_v1(int x) {
    if (x == Integer.MIN_VALUE) {
        return 0;
    }
    //保存符号标记,最后返回时使用
    int sign = x > 0 ? 1 : -1;
    //负数情况,转换成正数处理
    x = x * sign;

    String val = String.valueOf(x);
    char[] chars = val.toCharArray();
    int len = chars.length;
    char[] newCh = new char[len];

    for (int i = 0; i < len; i++) {
        newCh[i] = chars[len - 1 - i];
    }
    String reverseVal = String.valueOf(newCh);

    long result = Long.valueOf(reverseVal);
    if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
        return 0;
    }
    return (int) (result * sign);
}
public int reverse_v2(int x) {
    if (x == Integer.MIN_VALUE) {
        return 0;
    }
    int sign = x > 0 ? 1 : -1;
    x = x * sign;

    String val = String.valueOf(x);
    char[] chars = val.toCharArray();
    int len = chars.length;

    for (int start = 0, end = len - 1; start < len / 2; start++, end--) {
        char temp = chars[start];
        chars[start] = chars[end];
        chars[end] = temp;
    }
    String reverseVal = String.valueOf(chars);

    long result = Long.valueOf(reverseVal);
    if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
        return 0;
    }
    return (int) (result * sign);
}
public int reverse(int x) {
    if (x == Integer.MIN_VALUE) {
        return 0;
    }
    int sign = x > 0 ? 1 : -1;
    x = x * sign;

    long result = 0;
    int last = 0;
    while ((last = x % 10) != x) {
        //获取个位数
        result = result * 10 + last;
        x = x / 10;
    }
    result = result * 10 + last;    //最高位数字处理
    if (result > Integer.MAX_VALUE) {
        return 0;
    }
    return (int) (result * sign);
}
3.总结
上一篇下一篇

猜你喜欢

热点阅读