內容 :
題目描述
大家都知道二進制是由0和1兩種數字組成的,十進制轉二進制, 小明現在要玩一個遊戲, 就是由1數到n,每數到一個數, 這個數的二進制有多少個1, 小明就要站起多少次, 例如數到9, 由於其二進制為1001, 所以小明要站起來兩次, 為了知道自己能否應付這個遊戲, 請你為小明算出, 由1數到n他必須站起來多少次?
大家都知道二進制是由0和1兩種數字組成的,十進制轉二進制, 小明現在要玩一個遊戲, 就是由1數到n,每數到一個數, 這個數的二進制有多少個1, 小明就要站起多少次, 例如數到9, 由於其二進制為1001, 所以小明要站起來兩次, 為了知道自己能否應付這個遊戲, 請你為小明算出, 由1數到n他必須站起來多少次?
輸入說明 :
每一行有一個數字N (1≦N≦1,0000,0000)
輸出說明 :
請輸出小明總共要站起來的次數。請輸出mod 1000000000 之後的結果
範例輸入 :
12
範例輸出 :
22
提示 :
※ 數學、遞迴
Dim ans As Long, x As Long
回覆刪除Private Sub Form_Load()
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Input #1, x
Close #1
For i = 1 To x
Call two(i, ans)
Next i
Open App.Path & "\out.txt" For Output As #1
Print #1, ans
Close #1
End
End Sub
Public Sub two(ByVal c As Long, ByRef ans As Long)
Do
If c Mod 2 <> 0 Then ans = ans + 1
c = c \ 2
Loop Until c = 0
End Sub
BY 小白
Public Sub Form_Load()
回覆刪除Me.Hide
Open App.Path & "\out.txt" For Output As #2
Open App.Path & "\in.txt" For Input As #1
Input #1, x
b = 0
For i = 1 To x
b = b + mycount(i, "")
Next i
Print #2, b
Close #1
Close #2
End
End Sub
Public Function mycount(ByVal a, c) As Integer
If a = 0 Then
For i = 1 To Len(c)
If Mid(c, i, 1) = "1" Then mycount = mycount + 1
Next i
Else
c = (a Mod 2) & c
mycount = mycount(a \ 2, c)
End If
End Function
BY 阿揚
小白好,阿揚好,
回覆刪除1.你們的程式OK,如果不算最大數的話。
2.要想想數學。去寫寫1有幾個1,2有幾個1,3呢,4呢...
然後試著找出規律,用更快速的方式,去解題。
不然,題目中的最大數,要算到何時呢?
Dim check(100000) As Long
回覆刪除Public Sub Form_Load()
Open App.Path & "\out.txt" For Output As #2
Open App.Path & "\in.txt" For Input As #1
check(1) = 1: check(2) = 1
n = 2: m = 2
For q = 3 To 100000
If n - q <= 0 Then n = n * 2
If q - n <= 0 Then
check(q) = 1 + check(q - n / 2)
End If
Next q
Input #1, x
For i = 1 To x
b = i: k1 = 0
n = 134217728: m = 26
If i <= 100000 Then
k = k + check(i)
Else
here:
Do While n - b >= 0
n = n / 2
Loop
If (b - n) >= 0 Then
b = b - n
k1 = k1 + 1
If b <= 100000 Then
k = k + k1 + check(b)
Else
GoTo here
End If
End If
End If
Next i
Print #2, k
Close #1
Close #2
End Sub
阿揚
Dim a(10000000) As Long, Min As Long, Max As Long, b(10000000) As Long
回覆刪除Private Sub Form_Load()
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Input #1, x
Min = 2: Max = 4
a(1) = 1: b(1) = 1
a(2) = 1: b(2) = 2
For i = 3 To x
If i < Max Then
a(i) = a(i - Min) + 1
b(i) = b(i - 1) + a(i)
ElseIf i = Max Then
Min = Max: Max = Max * 2
a(i) = 1
b(i) = b(i - 1) + a(i)
End If
Next i
Open App.Path & "\out.txt" For Output As #2
Print #2, b(x)
Close #2
Close #1
End
End Sub
BY 小白