Java實(shí)現(xiàn)整數(shù)的逆序輸出的三種方法
Java實(shí)現(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("輸入一個(gè)整數(shù):"); int num = input.nextInt(); while (num!=0) { System.out.print(num % 10); num /= 10; } } }
第二種:非負(fù)整數(shù)的逆序輸出(結(jié)果String化)。
class Cycle02 { public static void main(String[] args) { //注意:num >=0 Scanner input = new Scanner(System.in); System.out.print("請輸入一個(gè)整數(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("請輸入一個(gè)整數(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()]。
當(dāng)然,還有更多的方法,避繁就簡吧。
到此這篇關(guān)于Java實(shí)現(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接口對應(yīng)的XML文件,需要的朋友可以參考下2023-05-05Java監(jiān)聽器三種實(shí)現(xiàn)方法代碼解析
這篇文章主要介紹了Java監(jiān)聽器三種實(shí)現(xiàn)方法代碼解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08struts2簡介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
Struts2框架是MVC流程框架,適合分層開發(fā),這篇文章主要為大家詳細(xì)介紹了struts2簡介的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09mybatis-puls中的resultMap數(shù)據(jù)映射
這篇文章主要介紹了mybatis-puls中的resultMap數(shù)據(jù)映射,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08java組件commons-fileupload實(shí)現(xiàn)文件上傳、下載、在線打開
這篇文章主要介紹了java組件commons-fileupload實(shí)現(xiàn)文件上傳、下載、在線打開,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10