Nine Digits Expression

Problem:

 

Insert + ,-,*,/ signs as necessary in the string 123456789 to form an expression that evaluates to a certain number.

 

Answer:

 

Sub test() getall 2009, 1 getall 2009, 2 End Sub Private Sub getall(ByVal theresult As Integer, Optional order As Byte = 1) Dim temp As Long, x(16) As String, op, i As Long, j As Long Dim out As String, all As Long, num As Integer num = 0 op = Array("+", "-", "*", "/", "") If order = 1 Then For i = 0 To 8 x(i * 2) = i + 1 Next ElseIf order = 2 Then For i = 0 To 8 x(i * 2) = 9 - i Next End If all = 5 ^ 8 - 1 For i = 0 To all temp = i For j = 1 To 8 x(j * 2 - 1) = op(temp Mod 5) temp = temp / 5 Next out = Replace(Join(x, ""), " ", "") If Evaluate(out) = theresult Then num = num + 1 Debug.Print "Solutions " & num & ":" & vbTab & out & "=" & theresult End If Next Debug.Print IIf(num, num, "No") & " solutions were found!" End Sub

 

It returns:

 

Solutions 1:    1*2345*6/7+8-9=2009
Solutions 2:    1/2*3*4*5*67+8-9=2009
Solutions 3:    1*2/3*45*67+8-9=2009
3 solutions were found!

 

Solutions 1:    9*8-7+6*54*3*2*1=2009
Solutions 2:    9+8*7+6*54*3*2*1=2009
Solutions 3:    9*8-7+6*54*3*2/1=2009
Solutions 4:    9+8*7+6*54*3*2/1=2009
4 solutions were found!

转载于:https://www.cnblogs.com/fengju/archive/2009/02/18/6336215.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值