Java examples for java.math:BigInteger
sum BigInteger Of Digits
//package com.java2s; import java.math.BigInteger; public class Main { public static void main(String[] argv) throws Exception { BigInteger bint = new BigInteger("1234"); System.out.println(sumOfDigits(bint)); }/*from w ww . j a v a 2 s . co m*/ public static BigInteger sumOfDigits(BigInteger bint) { BigInteger sum = BigInteger.ZERO; BigInteger currDigit = null; do { BigInteger divisor = findNearestPowerOfTen(bint); currDigit = bint.divide(divisor); sum = sum.add(currDigit); bint = bint.mod(divisor); } while (currDigit.compareTo(BigInteger.ZERO) > 0); return sum; } public static BigInteger findNearestPowerOfTen(BigInteger bint) { BigInteger divisor = BigInteger.ONE; int length = bint.toString().length(); for (int i = 0; i < length - 1; i++) { divisor = divisor.multiply(BigInteger.TEN); } return divisor; } }