OPT to H1B transition doubt

Hello my name is Denu,
I am on F1 visa and I have an OPT valid till Oct 12, 2017.
I applied for H1B this year and picked in the lottery but no update as of today.

If H1B is denied
I am planning to study in the USA and going to join for the spring 2018 semester.
I will transfer my SEVIS on the first week of Oct 2017, and I will get I20 for the semester starting on Jan 2018.

My question is that
My classes are starting in JAN 2018 but my OPT is expiring on OCT 2017 can I stay legally in USA.