博客
关于我
Java洛谷P1307 数字反转
阅读量:323 次
发布时间:2019-03-04

本文共 1073 字,大约阅读时间需要 3 分钟。

Java程序示例:去除末尾零并倒序输出数字

本文将展示一个Java程序,该程序能够读取一个整数,去除其末尾的零,并将剩余的数字按倒序输出。

代码概述

以下是完整的代码示例:

import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        int a = scanner.nextInt();        int count = 0;        // 去除末尾的零        while (a % 10 == 0) {            a = a / 10;            count++;        }        // 处理负数情况        if (a < 0) {            a = -a;            count++;        }        // 将数字转换为字符串        String str = String.valueOf(a);        // 倒序输出数字        for (int i = str.length() - 1; i >= 0; i--) {            if (count == 1 && i == str.length() - 1) {                System.out.print("-" + str.charAt(i));            } else {                System.out.print(str.charAt(i));            }        }        scanner.close();    }}

功能解析

  • 读取输入:使用Scanner类读取用户输入的整数。
  • 去除末尾零:通过循环不断将数字除以10,直到末尾不再是零。同时记录零的数量。
  • 处理负数情况:如果输入的数字为负数,先将其转换为正数,并增加一个计数器。
  • 字符串转换与反转:将数字转换为字符串,然后从末尾向前遍历,逐个字符输出。
  • 输出示例

    假设输入为-38000

    • 去除末尾零后,数字变为-380
    • 由于是负数,输出时会在首位添加-符号。
    • 最终输出结果为083-

    这个程序能够有效地去除末尾零,并将数字按倒序输出,适用于处理需要数字反转的场景。

    转载地址:http://naoq.baihongyu.com/

    你可能感兴趣的文章
    poj 3262 Protecting the Flowers 贪心
    查看>>
    poj 3264(简单线段树)
    查看>>
    Qt笔记——布局管理三件套分割窗口、停靠窗口和堆栈窗口
    查看>>
    poj 3277 线段树
    查看>>
    POJ 3349 Snowflake Snow Snowflakes
    查看>>
    POJ 3411 DFS
    查看>>
    poj 3422 Kaka's Matrix Travels (费用流 + 拆点)
    查看>>
    Qt笔记——官方文档全局定义(二)Functions函数
    查看>>
    POJ 3468 A Simple Problem with Integers
    查看>>
    poj 3468 A Simple Problem with Integers 降维线段树
    查看>>
    poj 3468 A Simple Problem with Integers(线段树 插线问线)
    查看>>
    poj 3485 区间选点
    查看>>
    poj 3518 Prime Gap
    查看>>
    poj 3539 Elevator——同余类bfs
    查看>>
    Qt笔记——官方文档全局定义(三)Macros宏
    查看>>
    poj 3628 Bookshelf 2
    查看>>
    Qt笔记——官方文档全局定义(一)Types数据类型
    查看>>
    POJ 3670 DP LIS?
    查看>>
    POJ 3683 Priest John's Busiest Day (算竞进阶习题)
    查看>>
    POJ 3988 Selecting courses
    查看>>