的数目的位数之和2 ^ 1000目的、之和、位数

2023-09-10 23:35:16 作者:隐身对其可见

2 ^ 15 = 32768和它的数字的总和是3 + 2 + 7 + 6 + 8 = 26

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

什么是数字2的功率1000(2 ^ 1000)?

What is the sum of the digits of the number 2 power of 1000 (2^1000)?

任何人都可以提供解决方案或算法,这个问题在java中?

Can anyone provide the solution or algorithm for this problem in java?

推荐答案

下面是我的解决办法:

public static void main(String[] args) {

	ArrayList<Integer> n = myPow(2, 100);

	int result = 0;
	for (Integer i : n) {
		result += i;
	}

	System.out.println(result);
}

public static ArrayList<Integer> myPow(int n, int p) {
	ArrayList<Integer> nl = new ArrayList<Integer>();
	for (char c : Integer.toString(n).toCharArray()) {
		nl.add(c - 48);
	}

	for (int i = 1; i < p; i++) {
		nl = mySum(nl, nl);
	}

	return nl;
}

public static ArrayList<Integer> mySum(ArrayList<Integer> n1, ArrayList<Integer> n2) {
	ArrayList<Integer> result = new ArrayList<Integer>();

	int carry = 0;

	int max = Math.max(n1.size(), n2.size());
	if (n1.size() != max)
		n1 = normalizeList(n1, max);
	if (n2.size() != max)
		n2 = normalizeList(n2, max);

	for (int i = max - 1; i >= 0; i--) {
		int n = n1.get(i) + n2.get(i) + carry;
		carry = 0;
		if (n > 9) {
			String s = Integer.toString(n);
			carry = s.charAt(0) - 48;
			result.add(0, s.charAt(s.length() - 1) - 48);
		} else
			result.add(0, n);
	}

	if (carry != 0)
		result.add(0, carry);

	return result;
}

public static ArrayList<Integer> normalizeList(ArrayList<Integer> l, int max) {
	int newSize = max - l.size();
	for (int i = 0; i < newSize; i++) {
		l.add(0, 0);
	}
	return l;
}

这code可以在许多方面得到改善......这只是证明你可以完美地做到这一点,而不BigInts。

This code can be improved in many ways ... it was just to prove you can perfectly do it without BigInts.

美中不足的是把每一个号码的清单。这样,你可以做基本的款项,如:

The catch is to transform each number to a list. That way you can do basic sums like:

123456
+   45
______
123501
 
精彩推荐