If the bug ends up being that annoying that it takes that long, then I take a break to ensure my mind is clear and fresh, then I literally walk through everything step-by-step until I find the problem. If I don't see the issue with what I wrote, then I suspect a bug in the deeper layers or a lack of understanding of the deeper layers on my part, so I begin to isolate everything and do the equivalent of unit test each part to ensure it works as expected. Even if it's the most obvious thing I check it anyway.
Needless to say I sketch things out a bit beforehand (sometimes by writing throw away code), then I write the code little pieces at a time, then I immediately test each section of code I've written while it's fresh in my mind. This helps ensure that what I'm writing doesn't run away from me.
Sometimes I write large amounts of code just to get better at debugging when the amount of code written is large, and to beat myself into make less mistakes, and to improve my ability to hold more in memory without getting confused or losing track of what I'm doing. Sometimes just to prove to myself that I can do it. I just do it again and again until I beat myself into submission. After every mistake or failure to do things the way I expect I say, "No, it's possible. No, it's possible," then I start again.
Working at a 9-5 for sometime, especially at a large shitty company, is often enough to have the ability to do this beaten out of you by less capable or stuck-in-their-ways Engineers who insist on saying you have to do things this way or that way or you'll have problems. Eventually you may get sick of their stupidity and begin to act out to find ways to keep yourself sharp, to prevent being watered down, and to keep things moving.
Just remember it's possible to get better at cranking out line after line of code without making very many mistakes, and it's possible to adjust the way you write code in such a way that if errors are introduced they'll be blatant and easy to identify.