โจทย์
Powers of two grow fast: 2^64 already has 20 digits and 2^2000 has over 600. Compute 2^n exactly and add up its decimal digits. Without big integers, keep the number as an array of digits and double it n times.
Implement digit_sum_power_of_two(n).
Input
n: The exponent.
Output
Return the sum of the decimal digits of 2^n.
เงื่อนไข
0 ≤ n ≤ 2000
ตัวอย่าง
อินพุต:
n = 10
ผลลัพธ์ที่คาดหวัง:
expected = 7
อินพุต:
long long n = 10;
ผลลัพธ์ที่คาดหวัง:
long long expected = 7;
อินพุต:
long n = 10;
ผลลัพธ์ที่คาดหวัง:
long expected = 7;
คำอธิบาย
2^10 = 1024 and 1 + 0 + 2 + 4 = 7.
อินพุต:
n = 0
ผลลัพธ์ที่คาดหวัง:
expected = 1
อินพุต:
long long n = 0;
ผลลัพธ์ที่คาดหวัง:
long long expected = 1;
อินพุต:
long n = 0;
ผลลัพธ์ที่คาดหวัง:
long expected = 1;
คำอธิบาย
2^0 = 1, so the digit sum is 1.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
2^n is 1 doubled n times.
คำใบ้ 2
Store digits with the lowest digit first so carries move toward the end of the array.
คำใบ้ 3
Add the digits only once the doubling is finished.
ความซับซ้อนที่คาดหวัง
O(n²) time, O(n) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน