leetcode -- 389、405

389. Find the Difference

Problem Description

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:
s = “abcd”
t = “abcde”
Output:
e
Explanation:
‘e’ is the letter that was added.

Solution Method

兩個hash表比較

char findTheDifference(char * s, char * t)
{
    int hashS[26], hashT[26];
    memset(hashS, 0, sizeof(int) * 26);
    memset(hashT, 0, sizeof(int) * 26);

    for (int i = 0; i < strlen(s); i++)
        hashS[s[i] - 'a'] ++;
    for (int i = 0; i < strlen(t); i++)
        hashT[t[i] - 'a'] ++;
    
    for (int i = 0; i < 26; i ++)
    {
        if (hashS[i] != hashT[i])
        {
            return i + 'a';
        }
    }
    return NULL;
}

在這裏插入圖片描述

405. Convert a Number to Hexadecimal

Problem Description

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

  • All letters in hexadecimal (a-f) must be in lowercase.
  • The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character ‘0’; otherwise, the first character in the hexadecimal string will not be the zero character.
  • The given number is guaranteed to fit within the range of a 32-bit signed integer.
  • You must not use any method provided by the library which converts/formats the number to hex directly.

Example 1:

Input:
26
Output:
“1a”

Example 2:

Input:
-1
Output:
“ffffffff”

Solution Method

char * toHex(int num)
{
    char arr[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    char * str = (char *) malloc (sizeof(char) * 1024);
    int t = 0;
    memset(str, '\0', sizeof(char) * 1024);
    for(int i = 0; i < 8; ++i) 
    {
        unsigned char ret = num & 0x0f;
        num >>= 4;
        str[t++] = arr[ret];
        if(num == 0) 
            break;
    }
    // 反轉
    int l = 0, r = t-1;
    while (l < r)
    {
        char temp = str[l];
        str[l] = str[r];
        str[r] = temp;
        l ++; r --;
    }
    return str;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章