解题思路
使用字符串处理方法实现整数倒序输出:
- 读入为字符串处理
- 分离负号处理
- 字符串反转后去除前导零
关键点
- 使用string处理输入
- 处理负号情况
- 去除反转后的前导零
代码
#include <bits/stdc++.h>
using namespace std;
void solve() {
string s;
cin >> s;
// 处理负号
if (s[0] == '-') {
cout << "-";
s = s.substr(1);
}
// 反转字符串
reverse(s.begin(), s.end());
// 去除前导零
string result;
bool found = false;
for (char c : s) {
if (!found && c == '0') continue;
found = true;
result += c;
}
// 处理全零的情况
if (result.empty()) result = "0";
cout << result << endl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
while (t--) {
solve();
}
return 0;
}
import java.util.*;
public class Main {
static void solve(Scanner sc) {
String s = sc.next();
// 处理负号
if (s.charAt(0) == '-') {
System.out.print("-");
s = s.substring(1);
}
// 反转字符串
StringBuilder sb = new StringBuilder(s);
sb.reverse();
s = sb.toString();
// 去除前导零
StringBuilder result = new StringBuilder();
boolean found = false;
for (char c : s.toCharArray()) {
if (!found && c == '0') continue;
found = true;
result.append(c);
}
// 处理全零的情况
if (result.length() == 0) result.append("0");
System.out.println(result);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = 1;
while (t-- > 0) {
solve(sc);
}
sc.close();
}
}
def solve():
s = input()
# 处理负号
if s[0] == '-':
print('-', end='')
s = s[1:]
# 反转字符串并去除前导零
s = s[::-1]
result = s.lstrip('0')
# 处理全零的情况
if not result:
result = '0'
print(result)
def main():
t = 1
while t:
solve()
t -= 1
if __name__ == "__main__":
main()
算法及复杂度
- 算法:字符串处理
- 时间复杂度:
,
为字符串长度
- 空间复杂度:
,需要存储结果字符串