diff --git a/Java/ShortURL.java b/Java/ShortURL.java index 66d340a..f83cea6 100644 --- a/Java/ShortURL.java +++ b/Java/ShortURL.java @@ -14,6 +14,9 @@ * * Source: https://github.com/delight-im/ShortURL (Apache License 2.0) */ + +import java.math.BigInteger; + public class ShortURL { public static final String ALPHABET = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_"; @@ -31,9 +34,42 @@ public static String encode(int num) { public static int decode(String str) { int num = 0; for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (ALPHABET.indexOf(c) < 0) { + num = -1; + break; + } num = num * BASE + ALPHABET.indexOf(str.charAt(i)); } return num; } + public static String encode(String num) throws NumberFormatException { + BigInteger bnum = new BigInteger(num); + BigInteger bBase = new BigInteger(Integer.toString(BASE)); + StringBuilder str = new StringBuilder(); + while (bnum.compareTo(BigInteger.ZERO) > 0) { + int n = bnum.mod(bBase).intValue(); + str.insert(0, ALPHABET.charAt(n)); + bnum = bnum.divide(bBase); + } + + return str.toString(); + } + + public static BigInteger decodeWithBigNumber(String str) { + BigInteger bNum = new BigInteger("0"); + BigInteger bBase = new BigInteger(Integer.toString(BASE)); + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (ALPHABET.indexOf(c) < 0) { + bNum = new BigInteger("-1"); + break; + } + BigInteger br = new BigInteger(Integer.toString(ALPHABET.indexOf(c))); + bNum = bNum.multiply(bBase).add(br); + } + + return bNum; + } } diff --git a/JavaScript/ShortURL.js b/JavaScript/ShortURL.js index 5e05282..1c2ead1 100644 --- a/JavaScript/ShortURL.js +++ b/JavaScript/ShortURL.js @@ -14,6 +14,9 @@ * * Source: https://github.com/delight-im/ShortURL (Apache License 2.0) */ + +var bigInt = require("big-integer"); + var ShortURL = new function() { var _alphabet = '23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_', @@ -28,6 +31,20 @@ var ShortURL = new function() { return str; }; + /** + * @param {num} input number represented by string + * @return {str} encoded short url + */ + this.encodeBigInteger = function (num) { + var str = ''; + var bNum = bigInt(num); + while (bNum.compare(0) == 1) { + str = _alphabet.charAt(bNum.mod(_base)) + str; + bNum = bNum.divide(_base); + } + return str; + } + this.decode = function(str) { var num = 0; for (var i = 0; i < str.length; i++) { @@ -36,4 +53,17 @@ var ShortURL = new function() { return num; }; + + /** + * @param {str} ShortURL represented by string + * @return {str} decoded number represented by string + */ + this.decodeBigInteger = function(str) { + var bNum = bigInt(0); + for (var i = 0; i < str.length; i++) { + bNum = bNum.multiply(_base).add(_alphabet.indexOf(str.charAt(i))); + } + return bNum; + } + };