-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtinyurl.cpp
More file actions
63 lines (54 loc) · 1.38 KB
/
tinyurl.cpp
File metadata and controls
63 lines (54 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* Program to convert lengthy urls to 6 character length tiny urls */
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
// Function to generate short urls from integer ID
string idToShortURL(long int n)
{
// Map to store 62 possible characters
char map[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string shorturl;
// Convert integer ID to base 62 number
while(n)
{
// Use above map to store actual character in short url
shorturl.push_back(map[n%62]);
n = n/62;
}
// Reverse shortURL to complete base conversion
reverse(shorturl.begin(), shorturl.end());
return shorturl;
}
// Function to get integer ID back from a short url
long int shortURLtoID(string shortURL)
{
long int id = 0; // initialize result
int i;
// A simple base conversion logic
for (i = 0; i < shortURL.length(); ++i)
{
if ('a' <= shortURL[i] && shortURL[i] <= 'z')
{
id = id*62 + shortURL[i] - 'a';
}
if ('A' <= shortURL[i] && shortURL[i] <= 'Z')
{
id = id*62 + shortURL[i] - 'A' + 26;
}
if ('0' <= shortURL[i] && shortURL[i] <= '9')
{
id = id*62 + shortURL[i] - '0' + 52;
}
}
return id;
}
// Driver program to test the above function
int main()
{
int n = 12345;
string shorturl = idToShortURL(n);
cout << "Generated short url is " << shorturl << endl;
cout << "Id from url is " << shortURLtoID(shorturl) << endl;
return 0;
}