stepping_number.cpp
This commit is contained in:
106
puzzles/interviews/training/stepping_number.cpp
Normal file
106
puzzles/interviews/training/stepping_number.cpp
Normal file
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
|
||||
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
|
||||
VIM-: let b:cppflags=g:Iboost.g:Itbb
|
||||
VIM-: let b:ldflags=g:Lboost.g:Ltbb
|
||||
VIM-: let b:ldlibpath=g:Bboost.g:Btbb
|
||||
VIM-: let b:argv=""
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
/*Given N and M find all stepping numbers in range N to M
|
||||
|
||||
The stepping number:
|
||||
|
||||
A number is called as a stepping number if the adjacent digits have a difference of 1.
|
||||
e.g 123 or 101 is stepping number, but 358 is not a stepping number
|
||||
|
||||
Example:
|
||||
|
||||
N = 10, M = 20
|
||||
all stepping numbers are 10 , 12
|
||||
|
||||
Return the numbers in sorted order.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Solution: complexity is linear actually. O(n)
|
||||
* So, a better solution I guess will be to interate over the range
|
||||
* and check each number on condition.
|
||||
*/
|
||||
|
||||
|
||||
void f( std::vector<int>& v, int A, int B, int n )
|
||||
{
|
||||
if ( A <= n && n <= B ) {
|
||||
v.push_back(n);
|
||||
}
|
||||
else if ( n > B ) {
|
||||
return;
|
||||
}
|
||||
|
||||
int d = n % 10;
|
||||
if ( d + 1 <= 9 ){
|
||||
f( v, A, B, n*10+d+1);
|
||||
}
|
||||
if ( d - 1 >= 0 ){
|
||||
f( v, A, B, n*10+d-1);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<int> stepnum(int A, int B)
|
||||
{
|
||||
std::vector<int> v;
|
||||
|
||||
if ( A <= 0 && 0 <= B ){
|
||||
v.push_back(0);
|
||||
}
|
||||
|
||||
for ( int i = 1; i <= 9; ++i ){
|
||||
f( v, A, B, i );
|
||||
}
|
||||
|
||||
std::sort(v.begin(), v.end());
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
void print( const std::vector<int>& A )
|
||||
{
|
||||
for (auto i: A){
|
||||
std::cout << i << " ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
int main ( void )
|
||||
{try{
|
||||
auto begin = std::chrono::high_resolution_clock::now();
|
||||
|
||||
|
||||
//......
|
||||
print( stepnum(10, 20) );
|
||||
print( stepnum(0, 1000) );
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> seconds = end - begin;
|
||||
std::cout << "Time: " << seconds.count() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
catch ( const std::exception& e )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "std::exception(\"" << e.what() << "\")." << std::endl;
|
||||
return 2;
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
std::cerr << std::endl
|
||||
<< "unknown exception." << std::endl;
|
||||
return 1;
|
||||
}}
|
||||
|
||||
Reference in New Issue
Block a user