博客
关于我
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/

    你可能感兴趣的文章
    thinkphp 常用SQL执行语句总结
    查看>>
    Oracle:ORA-00911: 无效字符
    查看>>
    Text-to-Image with Diffusion models的巅峰之作:深入解读 DALL·E 2
    查看>>
    TCP基本入门-简单认识一下什么是TCP
    查看>>
    tableviewcell 中使用autolayout自适应高度
    查看>>
    Orcale表被锁
    查看>>
    svn访问报错500
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    SQL-CLR 类型映射 (LINQ to SQL)
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
    查看>>