2012年11月5日 星期一

進位判斷


加法的運算是把2 個整數靠右對齊,然後由右至左,一位一位相加。如果相加的結果大於等於10 就有進位(carry)發生。請寫個程式來判斷兩個正整數相加時,產生了幾次進位的情況。

輸入說明:
第一行的數字,表示有幾組測試資料,第二行開始的每一行即為一筆測試資料。每一行
輸入的資料有兩個正整數,以一個空格分開,每個整數的長度均小於100 位數。
輸出說明:
對每一筆測試資料,輸出相加後有幾次進位的次數。
輸入範例:
2
123 456
555 555

2 則留言:

  1. Dim mycount, add, added, temp, times, ans As Integer
    Private Sub Form_Load()
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, mycount
    Do
    temp = 0
    ans = 0
    Input #1, add, added
    If Len(add) > Len(added) Then times = Len(add)
    If Len(added) > Len(add) Then times = Len(added)
    If Len(added) = Len(add) Then times = Len(added)

    For i = 1 To times
    If Val(Mid(add, i, 1)) + Val(Mid(added, i, 1)) + temp > 9 Then
    temp = 1
    ans = ans + 1
    Else
    temp = 0
    End If
    Next

    Print #2, ans
    Loop Until EOF(1)

    Close #2
    Close #1
    End Sub

    回覆刪除
  2. Dim k As Integer
    Private Sub Form_Load()
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, x
    For i = 1 To x
    Input #1, x, y
    c = Len(x)
    v = Len(y)
    If c > v Then
    y = "0" & y
    c = Len(y)
    Else
    If v > c Then
    x = "0" & x
    v = Len(x)
    End If
    End If
    e = 0
    For j = c To 1 Step -1
    a = Val(Mid(x, j, 1))
    b = Val(Mid(y, j, 1))
    w = a + b + e
    If w >= 10 Then
    e = 1
    w = w - 10
    k = k + 1
    Else
    e = 0
    End If
    ans = w & ans
    Next
    If e = 1 Then ans = "1" & ans
    Print #2, k
    k = 0
    ans = ""
    Next
    Close #2
    Close #1
    End
    End Sub

    回覆刪除