Java實現(xiàn)整數(shù)的逆序輸出的三種方法
Java實現(xiàn)整數(shù)的逆序輸出和C語言相似。下面我介紹三種方法。
第一種:無限制整數(shù)的逆序輸出。
import java.util.Scanner; class Cycle01 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("輸入一個整數(shù):"); int num = input.nextInt(); while (num!=0) { System.out.print(num % 10); num /= 10; } } }
第二種:非負整數(shù)的逆序輸出(結(jié)果String化)。
class Cycle02 { public static void main(String[] args) { //注意:num >=0 Scanner input = new Scanner(System.in); System.out.print("請輸入一個整數(shù):"); int num = input.nextInt(); String reverse = ""; while (num != 0) { reverse += num % 10; num /= 10; } System.out.println(reverse); } }
第三種:非特殊情況的逆序輸出(例如:非100,非10000等)
class Cycle03 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("請輸入一個整數(shù):"); int num = input.nextInt(); int result = 0; while(num!=0) { int x = num % 10; result = result * 10 + x; num /= 10; } System.out.println(result); } }
其他思路:
(1)定義數(shù)組,逆序輸出。
(2)將用戶輸入值視為字符串[String num = input.next()]。
當然,還有更多的方法,避繁就簡吧。
到此這篇關(guān)于Java實現(xiàn)整數(shù)的逆序輸出的三種方法的文章就介紹到這了,更多相關(guān)java整數(shù)的逆序輸出內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis中 mapper-locations和@MapperScan的作用
這篇文章主要介紹了Mybatis中 mapper-locations和@MapperScan的作用,mybatis.mapper-locations在SpringBoot配置文件中使用,作用是掃描Mapper接口對應的XML文件,需要的朋友可以參考下2023-05-05mybatis-puls中的resultMap數(shù)據(jù)映射
這篇文章主要介紹了mybatis-puls中的resultMap數(shù)據(jù)映射,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08java組件commons-fileupload實現(xiàn)文件上傳、下載、在線打開
這篇文章主要介紹了java組件commons-fileupload實現(xiàn)文件上傳、下載、在線打開,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-10-10