leetcode部分解题思路

1. A+B problem

  • Write a function that add two numbers A and B. You should not use + or any arithmetic operators.
  • 加法分两部分:按位异或得到当前位的值,按位与得到当前位产生的进位。
    1
    2
    3
    4
    int aplusb(int a, int b) {
    // write your code here, try to do it without arithmetic operators.
    return b == 0 ? a : aplusb(a^b, ((a&b) << 1));
    }

3. Digit Counts

  • Count the number of k’s between 0 and n. k can be 0 - 9.

  • 把数字转换成字符串来做,想法很新,值得注意,但是感觉复杂度还是很高。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int digitCounts(int k, int n) {
// write your code here
char k_ch=k+'0';
int count=0;
for(int i=0;i<=n;++i) {
string n_str=to_string(i);
int c=0;
for(int j=0;j<n_str.size();++j) {
if(n_str[j]==k_ch) ++c;
}
count+=c;
}
return count;
}

4. Ugly Number II

1
2
3
4
5
6
7
8
9
10
11
12
13
int nthUglyNumber(int n) {
vector<int> res(1, 1);
int i2 = 0, i3 = 0, i5 = 0;
while (res.size() < n) {
int m2 = res[i2] * 2, m3 = res[i3] * 3, m5 = res[i5] * 5;
int mn = min(m2, min(m3, m5));
if (mn == m2) ++i2;
if (mn == m3) ++i3;
if (mn == m5) ++i5;
res.push_back(mn);
}
return res.back();
}