2012年11月5日 星期一

簡易大數減法


輸入兩數N1、N2,做大數的減法。 (N1、N2皆無限制)

輸入:
1000000000000000000000000
1

輸出:
999999999999999999999999

2 則留言:

  1. Dim sub1, sub2, ans As String
    Dim ok As Boolean
    Private Sub Form_Load()
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Line Input #1, sub1
    Line Input #1, sub2
    Do
    If Val(Right(sub1, Len(sub2))) >= Val(sub2) Then
    okk = Str((Val(Right(sub1, Len(sub2))) - Val(sub2)))
    sub1 = Left(sub1, Len(sub1) - Len(sub2))
    sub1 = sub1 & okk
    sub1 = Replace(sub1, " ", "")
    sub2 = 0
    ok = True
    Print #2, sub1
    Else
    For i = Len(sub1) - Len(sub2) To 1 Step -1
    If Val(Mid(sub1, i, 1)) <> 0 Then
    For ii = 1 To i - 1
    ans = ans & Mid(sub1, ii, 1)
    Next

    midd = Val(Mid(sub1, i, 1)) - 1
    ans = ans & midd

    For iii = i + 1 To Len(sub1)
    ans = ans & Str(Val(Mid(sub1, iii, 1)) + 9)
    Next
    sub2 = Str(Val(sub2) - 1)
    sub1 = Replace(ans, " ", "")
    If Mid(sub1, 1, 1) = 0 Then sub1 = Right(sub1, Len(sub1) - 1)
    ok = False
    End If
    Next
    End If

    Loop Until ok = True
    Close #2
    Close #1
    End Sub

    回覆刪除
  2. Dim ans As String, s As Integer
    Dim XIsBig As Boolean
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "/in.txt" For Input As #1
    Open App.Path & "/out.txt" For Output As #2

    Line Input #1, x
    Line Input #1, y

    Do Until Len(x) = Len(y)
    If Len(x) > Len(y) Then
    y = "0" & y
    Else
    x = "0" & x
    End If
    Loop

    ' 先假設X(第一個測資) 比較大
    XIsBig = True
    '如果取X與Y的第一個字比大小,如果Y比較大,代表第二次測資比較大
    '此時將XY互相交換,一樣由大減小,只是輸出時加個負號
    If Val(Mid(x, 1, 1)) < Val(Mid(y, 1, 1)) Then
    XIsBig = False
    tmp = x: x = y: y = tmp
    End If
    ans = "": s = 0

    For i = Len(x) To 1 Step -1
    s1 = Val(Mid(x, i, 1)): s2 = Val(Mid(y, i, 1))
    If s1 - s >= s2 Then
    ' 需額外判斷是否i=1(到最前面的數字)的情形
    If i > 1 Then
    ans = (s1 - s2 - s) & ans
    s = 0
    Else
    '如果i=1,且s1-s不等於s2,就能直接做
    If s1 - s > s2 Then ans = (s1 - s2 - s) & ans
    End If
    Else
    If i = 1 Then
    ans = (s1 - s2 - s) & ans
    Else
    ans = (s1 + 10 - s - s2) & ans
    s = 1
    End If
    End If
    Next i

    If XIsBig = True Then Print #2, ans Else Print #2, "-" & ans
    Close
    End
    End Sub

    回覆刪除