I know google translate does the bare minimum job of translating a sentence into Japanese. The original sentence was, "I had to hit my head on the table." which was translated into "テーブルに頭を打たなければなりませんでした。" I tried changing the position of the object because it made more sense to me. The translated sentence I came up with was, "頭をテーブルに打たなければなりませんでした。" Can we use this instead?
Also, "打たなければなりませんでした。" seems a bit confusing. It translates to "I had to hit." but doesn't なければ mean "If not" and I don't know why "なりませんでした" was used.