LeetCode #6 (#58, #66, #67)

58. Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:

Input: "Hello World"
Output: 5
//Solution
//总结:遍历新单词重置即可
int lengthOfLastWord(char * s){
    int len= 0;
    while (*s) {
        while (*s==' ') ++s; //跳过空格
        if (*s) {   
            len=0; // 遇到新的单词重置
            while (*s && *s !=' ') { ++s; ++len; }
        }
    }
    return len;
}

66. Plus One

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
//Solution
//总结:倒着判断,逐个求,最后判断是否进了一位
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* plusOne(int* digits, int digitsSize, int* returnSize){
    int i,j,k=1;
    int*res=(int*)malloc(sizeof(int)*(digitsSize+1));
    for(i=digitsSize-1;i>=0;i--)
    {
        j=(digits[i]+k)%10;
        res[i+1]=j;
        k=(digits[i]+k)/10;
    }
    if(res[1]==0)
    {   
        *returnSize=digitsSize+1;
        res[0]=1;
        return res;
    }
    else
    {   
        *returnSize=digitsSize; 
        return res+1;
    } 
}
67. Add Binary

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Constraints:

  • Each string consists only of '0' or '1' characters.
  • 1 <= a.length, b.length <= 10^4
  • Each string is either "0" or doesn’t contain any leading zero.
//Solution
//总结:就是还是倒着来,遍历后对每位判断,进行求和异或操作
char * addBinary(char * a, char * b){
    int lena = strlen(a), lenb = strlen(b), carry = 0;
    int lenc = lena > lenb?lena:lenb;
    char * c = malloc(lenc+2);//防止溢出
    c[lenc+1] = '\0';
    while(lena || lenb ){
        if(lena) carry += (a[--lena]-'0');
        if(lenb) carry += (b[--lenb]-'0');
        c[lenc--] = (carry&1)+'0';
        carry >>= 1;
    }
    c[0] = carry+'0';
    return c+(carry^1);
}
发布了72 篇原创文章 · 获赞 10 · 访问量 5840

猜你喜欢

转载自blog.csdn.net/weixin_44198992/article/details/105338151