split int value into separate digits

后端 未结 8 1886
野的像风
野的像风 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:19

    This will split the digits for you. Now put them into an array instead of printing them out and do whatever you want with the digits. If you want to add them, you could replace the System.out with something like sum += z;.

    public class Splitter {
        public static int numLength(int n) {
            int length;        
            for (length = 1; n % Math.pow(10, length) != n; length++) {}        
            return length;
        }
        public static void splitNums(double x){
            double y, z, t = x;   
    
            for (int p = numLength((int)x)-1; p >= 1; p--){
                 y = t % Math.pow(10, (numLength((int)(t))-1));
                 z = ((t - y)/Math.pow(10, p));             
                 t = t - (z * Math.pow(10, p)); 
    
                 System.out.println(Math.abs((int)(z)));
            }   
            System.out.println(Math.abs((int)(t)));          
        }
    }
    

提交回复
热议问题