Thursday 25 August 2016

Project Euler Problem 16: Power digit sum

Problem

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?

Solution

Nothing fancy here. Just implement my own multiply by 2 algorithm.

 private static final int N = 1000;  
      public static void main(String[] args) {  
           String result = "1";  
           for (int i = 1; i<=N; i++){  
                result = times2(result);  
           }  
           System.out.println(sumDigits(result));  
      }  
      private static String times2(String num){  
           String result = "";  
           int carryOver = 0;  
           for (int i = num.length()-1; i>=0; i--){  
                int temp = Integer.parseInt(num.charAt(i)+"") * 2 + carryOver;  
                result = String.valueOf(temp % 10) + result;  
                carryOver = temp >= 10 ? 1 : 0;  
           }  
           if (carryOver == 1){  
                result = "1"+result;  
           }  
           return result;  
      }  
      private static int sumDigits(String num){  
           int result = 0;  
           for (int i = 0; i<num.length(); i++){  
                result += Integer.parseInt(num.charAt(i)+"");  
           }  
           return result;  
      }  

No comments:

Post a Comment