The answer is grace.
David, and Saul, and Rahab, and others, are the "exceptions that prove the rule."
All of them had faith in God, and specifically in David and Saul's/Paul's case, and almost certainly Rahab's case, they humbled themselves and repented of their sin and asked for forgiveness...