Iterate through each digit in a number

后端 未结 5 745
星月不相逢
星月不相逢 2020-12-15 07:41

I am trying to create a program that will tell if a number given to it is a \"Happy Number\" or not. Finding a happy number requires each digit in the number to be squared,

5条回答
  •  自闭症患者
    2020-12-15 08:02

    I wondered which method would be quickest to split up a positive number into its digits in Java, String vs modulo

      public static ArrayList splitViaString(long number) {
    
        ArrayList result = new ArrayList<>();
        String s = Long.toString(number);
    
        for (int i = 0; i < s.length(); i++) {
          result.add(s.charAt(i) - '0');
        }
        return result; // MSD at start of list
      }
    

    vs

      public static ArrayList splitViaModulo(long number) {
    
        ArrayList result = new ArrayList<>();
    
        while (number > 0) {
          int digit = (int) (number % 10);
          result.add(digit);
          number /= 10;
        }
        return result; // LSD at start of list
      }
    

    Testing each method by passing Long.MAX_VALUE 10,000,000 times, the string version took 2.090 seconds and the modulo version 2.334 seconds. (Oracle Java 8 on 64bit Ubuntu running in Eclipse Neon)

    So not a lot in it really, but I was a bit surprised that String was faster

提交回复
热议问题