This is a quote from Psalm 32:1-2. This psalm was written by David after his adultery with Bathsheba and his murder of her husband (2 Sam. 11). Read: Psalm 32:1-5
The reason that God imputed His own righteousness to David rather than his lawless deeds is because he believed in the promise of the Messiah/Savior who would take away the sins of the world. What a tremendous blessing it is to receive the righteousness of God rather than a one-way ticket to the Lake of Fire.

“The disparity between legalism and grace is seen most clearly in the way God grants a right standing to people of faith.” [rather than of works]

When O.T. believers believed the gospel, their sins were forgiven and when they acknowledged their sins to God, their sins were also forgiven (Psa. 32:5).

The point is 'forgiveness of sin' is a 'take away' or subtraction. Imputation of divine righteousness is an addition. It is the 'addition' of the imputation of divine righteousness that permits saved humans to live with a perfect God - and we do not earn it or deserve it - it is a gift from God.

When a believer acknowledges his sin to God, it is impossible for Him to still impute sin to him or refuse to forgive him.

Psalm 103:11-12 For as the heavens are high above the earth, So great is His mercy toward those who fear Him; 12) As far as the east is from the west, So far has He removed our transgressions from us.