Press "Enter" to skip to content

Posts tagged as “conversion”

花花酱 LeetCode 504. Base 7


Given an integer, return its base 7 string representation.

Example 1:

Input: 100
Output: "202"

Example 2:

Input: -7
Output: "-10"

Note: The input will be in range of [-1e7, 1e7].

Solution: Simulation

Time complexity: O(logn)

Space complexity: O(logn)


花花酱 LeetCode 800. Simple RGB Color


In the following, every capital letter represents some hexadecimal digit from 0 to f.

The red-green-blue color "#AABBCC" can be written as "#ABC" in shorthand.  For example, "#15c" is shorthand for the color "#1155cc".

Now, say the similarity between two colors "#ABCDEF" and "#UVWXYZ" is -(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2.

Given the color "#ABCDEF", return a 7 character color that is most similar to #ABCDEF, and has a shorthand (that is, it can be represented as some "#XYZ"

Example 1:
Input: color = "#09f166"
Output: "#11ee66"
The similarity is -(0x09 - 0x11)^2 -(0xf1 - 0xee)^2 - (0x66 - 0x66)^2 = -64 -9 -0 = -73.
This is the highest among any shorthand color.


  • color is a string of length 7.
  • color is a valid RGB color: for i > 0color[i] is a hexadecimal digit from 0 to f
  • Any answer which has the same (highest) similarity as the best answer will be accepted.
  • All inputs and outputs should use lowercase letters, and the output is 7 characters.

Solution: Brute Force

R, G, B are independent, find the closest color for each channel separately.

Time complexity: O(3 * 16)

Space complexity: O(1)


花花酱 LeetCode 297. Serialize and Deserialize Binary Tree


Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.



Time Complexity O(n)

Solution 1: ASCII


Solution 2: Binary


C++ (string)

Related Problems