笔试题 把正整数n的每一位拆分出来,存放到数组中

把正整数n的每一位拆分出来,存放到数组中。例如123的拆分结果为[1,2,3],不能调用数字转字符串函数

public class DigitSplitter {  
  
    public static int[] splitDigits(int n) {  
        // 初始化一个足够大的数组来存储数字(假设n不会超过Integer.MAX_VALUE)  
        int[] digits = new int[11]; // Integer.MAX_VALUE有10位数字,加上一个额外的位置以防万一(虽然实际上不会用到)  
        int index = 0;  
  
        // 循环直到n变为0  
        while (n > 0) {  
            // 获取最低位的数字,并将其存储在数组中  
            digits[index] = n % 10;  
            // 去掉最低位的数字  
            n = n / 10;  
            // 移动到数组的下一个位置  
            index++;  
        }  
  
        // 创建一个新的数组,只包含实际的数字(去掉多余的空间)  
        int[] result = new int[index];  
        System.arraycopy(digits, 0, result, 0, index);  
  
        // 由于是从低位到高位存储的,需要反转数组  
        reverseArray(result);  
  
        return result;  
    }  
  
    // 辅助方法:反转数组  
    private static void reverseArray(int[] array) {  
        int left = 0;  
        int right = array.length - 1;  
        while (left < right) {  
            // 交换左右两边的元素  
            int temp = array[left];  
            array[left] = array[right];  
            array[right] = temp;  
            // 移动指针  
            left++;  
            right--;  
        }  
    }  
  
    public static void main(String[] args) {  
        int n = 123;  
        int[] result = splitDigits(n);  
  
        // 打印结果  
        for (int digit : result) {  
            System.out.print(digit + " ");  
        }  
    }  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值