split int value into separate digits

后端 未结 8 1837
野的像风
野的像风 2020-11-27 18:43

I want to split my int value into digits. eg if the no. is 542, the result should be 5,4,2.

I have 2 options. 1) Convert int into String & then by using getCharA

相关标签:
8条回答
  • 2020-11-27 19:23

    Use the mod 10 rule...

     List<Integer> digits = new ArrayList<Integer>();
     while (n > 0) {
         digits.add(n%10);
         n/=10;
     }
    
    0 讨论(0)
  • 2020-11-27 19:27
    List<Integer> digits(int i) {
        List<Integer> digits = new ArrayList<Integer>();
        while(i > 0) {
            digits.add(i % 10);
            i /= 10;
        }
        return digits;
    }
    
    0 讨论(0)
提交回复
热议问题