7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

C++:

class Solution {
public:
    int reverse(int x) {
        int min = -2147483648, max = 2147483647;
        long long res = 0;
        while(x!=0) {
            res = res * 10 + x % 10;
            x = x / 10;
        }
        return res > max || res < min ? 0 : res;
    }
};

 C:

int reverse(int x){
    int min = -2147483648, max = 2147483647;
    long res = 0;
    while(x!=0) {
        res = res * 10 + x % 10;
        x = x / 10;
    }
    return res > max || res < min ? 0 : res;
}

 

`java.lang.NumberFormatException: For input string: "A"` 异常表明在将字符串转换为整数时,输入的字符串不是有效的整数格式。在原代码中,使用 `Integer.parseInt(s)` 尝试将输入的字符串转换为整数,当输入包含非数字字符(如 "A")时,就会抛出该异常。 为了解决这个问题,可以将节点的数据类型从 `int` 改为 `String`,并相应地修改代码。以下是修改后的代码: ```java import java.util.Scanner; // 定义链表节点类 class ListNode { String data; ListNode next; ListNode(String data) { this.data = data; this.next = null; } } // 定义链表类 class LinkedList { ListNode head; LinkedList() { this.head = null; } // 插入节点到链表尾部 void insert(String data) { ListNode newNode = new ListNode(data); if (head == null) { head = newNode; } else { ListNode temp = head; while (temp.next != null) { temp = temp.next; } temp.next = newNode; } } // 打印链表 void printList() { ListNode temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } // 单链表逆置 void reverseList() { ListNode prev = null; ListNode curr = head; ListNode next = null; while (curr != null) { next = curr.next; curr.next = prev; prev = curr; curr = next; } head = prev; } } public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] input = scanner.nextLine().split(" "); LinkedList list = new LinkedList(); // 构建单链表 for (String s : input) { list.insert(s); } // 输出逆置前的单链表 System.out.println("逆置前的单链表:"); list.printList(); // 逆置单链表 list.reverseList(); // 输出逆置后的单链表 System.out.println("逆置后的单链表:"); list.printList(); scanner.close(); } } ``` ### 代码解释 1. **链表节点类**:将 `ListNode` 类中的 `data` 类型从 `int` 改为 `String`。 2. **插入节点**:`insert` 方法接受 `String` 类型的参数。 3. **打印链表**:`printList` 方法打印 `String` 类型的数据。 4. **主函数**:在构建单链表时,直接将输入的字符串插入到链表中,不再进行整数转换。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值