CSharp · Console
// Write a program that inputs number n > 0 and prints number of decimal digits in n.
// The program should use only integer numbers and only basic integer operations
// (addition, subtraction, multiplication, division).
using System;
using System.Diagnostics;
public class Program
{
public static int InputInt(string prompt)
{
Console.Write("Enter " + prompt + ": ");
return Convert.ToInt32(Console.ReadLine());
}
public static void Main(string[] args)
{
int n = InputInt("n");
Trace.Assert(n > 0);
int d = 0;
int ten_power_d = 1;
// invariant: ten_power_d = 10**d and 10**d <= n
while (ten_power_d * 10 <= n)
{
// ten_power_d = 10**d and 10**(d+1) <= n
d++;
// ten_power_d = 10**(d-1) and 10**d <= n
ten_power_d = 10 * ten_power_d;
// ten_power_d = 10**d and 10**d <= n
}
// 10**d <= n and n < 10**(d+1) => n contains d+1 digits
Console.WriteLine("Number {0} has {1} decimal digits", n, d+1);
// Time = O(log n)
}
}