Project Euler | Problem 16 | Power digit sum
Problem Description:
2^15= 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
Concept:
Java Program:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex.projecteuler; | |
import java.math.BigInteger; | |
/** | |
* | |
* @author Rohit Agarwal | |
* @category Project Euler Problems | |
* @Problem 16 - Power Digit Sum. | |
* | |
*/ | |
public class Problem16 { | |
public static void main(String[] args) { | |
int a = 2; | |
int b = 1000; | |
// Converting Integer to BigInteger. | |
BigInteger number = new BigInteger(String.valueOf(a)); | |
// Getting 2^1000. | |
BigInteger power = number.pow(b); | |
// Converting BigInteger to String. | |
String powerInString = String.valueOf(power); | |
int length = powerInString.length(); | |
int sum = 0; | |
int temp = 0; | |
for (int i = 0; i < length; i++) { | |
// Converting char to int. | |
temp = powerInString.charAt(i) - 48; | |
sum += temp; | |
} | |
System.out.println("The sum of the digits of the number 2^1000 is : " + sum); | |
} | |
} |
Output:
![]() |
Figure2 |
Similar Problems:
References:
https://projecteuler.net/problem=16
https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html
Thank you friends, I hope you have clearly understood the solution of this problem. If you have any doubt, suggestion or query please feel free to comment below. You can also discuss this solution in our forum.
https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html
Thank you friends, I hope you have clearly understood the solution of this problem. If you have any doubt, suggestion or query please feel free to comment below. You can also discuss this solution in our forum.
Project Euler | Problem 16 | Power digit sum
Reviewed by Rohit Agarwal
on
10/15/2017
Rating:

why did you use -48
ReplyDeleteBecause ascii value of 0-9 digit is 48-57 and on subtracting two ascii values, we will get integer.
ReplyDelete