Leetcode Weekly Contest 167:Sequential Digits

1291. Sequential Digits

class Solution {
public:
    vector<int> sequentialDigits(int low, int high){
        string total="123456789";
        int low_num=get_length(low);
        int hight_num=get_length(high);
        vector<int> res;
        
        for(int n=low_num;n<hight_num+1;n++){
            for(int i=0;i<= 9-n;i++){
                int temp = stoi(total.substr(i,n));
                if( temp >= low && temp <= high)
                    res.push_back(temp);
            }
                        
        }
        return res;
    }
    
int get_length(int x)
{
	using namespace std;
	int leng=0;
	while(x)
	{
		x/=10;
		leng++;
	}
	return leng;
}
    
};

自己没有写完,主要是对计算整数的位数,不熟悉语言函数

优秀代码

class Solution 
{
    public:
    vector<int> sequentialDigits(int low, int high) 
    {
        vector<int> result;
        int left=to_string(low).length(), right=to_string(high).length();
        string total="123456789";
        
        for(int i=left;i<=right;i++)
            for(int j=0;j<10-i;j++)
                if(stoi(total.substr(j,i))>=low&&stoi(total.substr(j,i))<=high)
                    result.push_back(stoi(total.substr(j,i)));

        return result;
    }
};

反思与学习
对于整数求位数,可以采用to_string 先变成string格式,再利用string的.length()可以直接获取这个长度。

发布了46 篇原创文章 · 获赞 0 · 访问量 855

猜你喜欢

转载自blog.csdn.net/github_38148039/article/details/103548251