Remove 9 in C++


Suppose we have an integer n, we have to return nth integer after following this operation: Start from integer 1, remove any integer that contains 9 such as 9, 19, 29... So now, we will have a new integer sequence like 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ... We have to keep in mind that 1 will be the first integer.

So, if the input is like 9, then the output will be 10

To solve this, we will follow these steps −

  • ret := 0

  • s := 1

  • while n is non-zero, do −

    • ret := ret + (n mod 9) * s

    • n := n / 9

    • s := s * 10

  • s := s * 10

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
   public:
   int newInteger(int n) {
      int ret = 0;
      lli s = 1;
      while (n) {
         ret += (n % 9) * s;
         n /= 9;
         s *= 10;
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.newInteger(120));
}

Input

120

Output

143

Updated on: 11-Jul-2020

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements