โจทย์
Count how many decimal digits n has when written normally, without leading zeros.
Implement count_digits(n).
Input
n: A positive integer.
Output
Return the number of digits.
เงื่อนไข
1 ≤ n ≤ 10¹⁸
ตัวอย่าง
อินพุต:
n = 352
ผลลัพธ์ที่คาดหวัง:
expected = 3
อินพุต:
long long n = 352;
ผลลัพธ์ที่คาดหวัง:
long long expected = 3;
อินพุต:
long n = 352;
ผลลัพธ์ที่คาดหวัง:
long expected = 3;
คำอธิบาย
352 has three digits.
อินพุต:
n = 7
ผลลัพธ์ที่คาดหวัง:
expected = 1
อินพุต:
long long n = 7;
ผลลัพธ์ที่คาดหวัง:
long long expected = 1;
อินพุต:
long n = 7;
ผลลัพธ์ที่คาดหวัง:
long expected = 1;
คำอธิบาย
A single digit.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
You only need to know how many times you can remove a digit before nothing remains.
คำใบ้ 2
A loop with division by 10 or a string length both work well.
คำใบ้ 3
Don’t forget that any positive single-digit number still has exactly one digit.
ความซับซ้อนที่คาดหวัง
O(d) time, O(1) extra space