Digits Sequence-关于Stringstream

Stringstream

  • stringsteam 用于进行数据类型转换,<sstream> 库定义了三种类:istringstreamostringstreamstringstream,分别用来进行流的输入、输出和输入输出操作。
  • 接下来举一个栗子,通过这道题我们来介绍下从 int 转化为 string 的过程

Digits Sequence (Easy Edition)

  • 这道题是一道很水的题,我们通过这道题来介绍下 \(streamstring\)
  • 我们可以考虑把每一个字符都压入 \(s\),最后输出第 \(n-1\) 项即可
  • 总体来说,streamstringstring 的使用极为相似
    • stringstream:\(s.str().size()\)(取长)。
    • string:取长就不必多说了
  • 有没有发现区别就是中间多了个\(.str()\)
  • 接下来就是一点也不激动人心的代码了:
#include<bits/stdc++.h>//Forever_chen
#define RT register
using namespace std;
template<class t> inline t read(t &x){
    char c=getchar();bool f=0;x=0;
    while(!isdigit(c)) f|=c=='-',c=getchar();
    while(isdigit(c))x=(x<<1)+(x<<3)+(c^48),c=getchar();
    if(f)x=-x;return x;
}
template<class t>inline void write(t x){
    if(x<0)putchar('-'),write(-x);
    else{if(x>9)write(x/10);putchar('0'+x%10);}
}
template<class t>inline void writeln(t x){
    write(x);putchar('\n');
    return;
}
template<class t>inline void write_blank(t x){
    write(x);putchar(' ');
    return;
}
int n,k;
stringstream s; //定义一个stringstream类型的s
signed main(){
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    read(n);
    for(int i=1;s.str().size()<=n;i++){//取长,和string类型相类似
        s<<i;//将int类型的i压入s
    }
    cout<<s.str()[n-1];//输出第n-1项
    //system("pause");
    return 0;
}

Digits Sequence (Hard Edition)

  • 由于这题比较阿巴的复杂度,我们无法用 stringstream 去完成代码
  • 我们考虑位数,枚举位数,将小于输入的数的位数的数全部扔掉,再判断当前字符所在的数,最后求字符所在当前数的位置(本人不善于表达,说得比较绕,建议直接食用代码)。代码比较简单。
  • 接下来就是一点也不激动人心的代码了:
#include<bits/stdc++.h>//Forever_chen
#define RT register
using namespace std;
template<class t> inline t read(t &x){
    char c=getchar();bool f=0;x=0;
    while(!isdigit(c)) f|=c=='-',c=getchar();
    while(isdigit(c))x=(x<<1)+(x<<3)+(c^48),c=getchar();
    if(f)x=-x;return x;
}
template<class t>inline void write(t x){
    if(x<0)putchar('-'),write(-x);
    else{if(x>9)write(x/10);putchar('0'+x%10);}
}
template<class t>inline void writeln(t x){
    write(x);putchar('\n');
    return;
}
template<class t>inline void write_blank(t x){
    write(x);putchar(' ');
    return;
}
long long n,len=1,num=1;
signed main(){
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    read(n);
    while(1){
        if(n<num*9*len){
            num=num+n/len+(n%len>0)-1;
            n=len-(n%len?n%len:len);
            while(n--){
                num/=10;
            } 
            write(num%10);
            return 0;
        }
        else{
            n-=num*9*len++;
            num*=10;
        }
    }
    //system("pause");
    return 0;
}

原文链接: https://www.cnblogs.com/Forever-chen/p/12866971.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    Digits Sequence-关于Stringstream

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/347943

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午4:47
下一篇 2023年3月2日 上午4:47

相关推荐