首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 任意整數分解個十百千萬位:通用算法與數組實戰案例

     編輯:Java 綜合教學

Java 任意整數分解個十百千萬位:通用算法與數組實戰案例

將整數按位拆解是基礎算法訓練常客。本文提供從固定位數到任意長度的通用解法,並展示一個支援萬億級、帶中文單位輸出的完整控制台交互程序。

一、固定位數拆解 (以 3 位為例)

int num = 53;
int ge  = num % 10;        // 3
int shi = (num / 10) % 10; // 5
int bai = num / 100;       // 0

規律:第 n 位 (0-index) = (num / 10^n) % 10

二、通用任意長度拆解算法

public static List<Integer> splitDigits(long num) {
    List<Integer> digits = new ArrayList<>();
    if (num == 0) { digits.add(0); return digits; }
    boolean negative = num < 0;
    num = Math.abs(num);
    while (num > 0) {
        digits.add(0, (int)(num % 10)); // 头插保持高位在前
        num /= 10;
    }
    if (negative) digits.add(0, -1); // 标记负号
    return digits;
}

三、完整交互程序:支援萬億級 + 中文單位

import java.util.Scanner;
public class NumberSplitter {
    private static final String[] UNITS = 
        {"", "十", "百", "千", "萬", "十萬", "百萬", "千萬", "億", "十億", "百億", "千億", "萬億"};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("請輸入一個整數 (支援 ±9999 億): ");
        long num = sc.nextLong();
        sc.close();

        if (num == 0) { System.out.println("個位: 0"); return; }

        boolean neg = num < 0;
        num = Math.abs(num);
        int pos = 0;
        while (num > 0) {
            int digit = (int)(num % 10);
            String unit = (pos < UNITS.length) ? UNITS[pos] : "10^" + pos;
            System.out.printf("%s位 (%s): %d%n", unit.isEmpty()?"個":unit, unit, digit);
            num /= 10;
            pos++;
        }
        if (neg) System.out.println("符號: 負數");
    }
}

四、運行示例

請輸入一個整數: 123456789
個位: 9
十位: 8
百位: 7
千位: 6
萬位: 5
十萬位: 4
百萬位: 3
千萬位: 2
億位: 1

五、核心知識點總結

  • % 10 取末位,/= 10 右移一位,循環直到 0
  • long 支援 ±922京 (19 位),足夠大多數業務場景
  • 超大整數請用 BigInteger 配合 divideAndRemainder
  • 負數處理:取絕對值拆解,單獨標記符號
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved