原文出處
程式人員的面試心得及基本原則
VB版程式碼,有另外加上執行時間的紀錄
以n = 100億
執行最初的那個程式碼用Pentium M 1.3GHz約390秒左右
跑偷吃步那個考官的算法
約....0.0005秒....
這是一開始作者的寫法(應該吧@@)
Module Module1
Sub Main()
Console.Write("請輸入n:")
Dim n As Long
Dim i As Long
Dim Temp As Long
Dim Flag As Integer = 1
Dim Sum As Long
Dim StartTime As Single
Dim TotalTime As Single
n = Console.ReadLine()
StartTime = Timer
For i = 1 To n
Temp = Flag * i
Flag = (-1) * Flag
'Console.WriteLine(i)
Sum = Sum + Temp
Next
TotalTime = Timer - StartTime
Console.WriteLine(Format(TotalTime, "0.######"))
Console.WriteLine(Sum)
Console.Read()
End Sub
End Module
===============
這是考官的寫法
Module Module1
Sub Main()
Console.Write("請輸入n:")
Dim n As Long
Dim Sum As Long
Dim StartTime As Single
Dim TotalTime As Single
n = Console.ReadLine()
StartTime = Timer
If n Mod 2 = 0 Then
Sum = (n / 2) * -1
Else
Sum = (n / 2) * -1 + n
End If
TotalTime = Timer - StartTime
Console.WriteLine(Format(TotalTime, "0.######"))
Console.WriteLine(Sum)
Console.Read()
End Sub
End Module
留言列表