C/CPP中int和string的互相转换详解与多解例题分析

简介: C标准库atoi, atof, atol, atoll(C++11标准) 函数,以及sprintf、sscanf函数,用sstream类,实现C++中int和string的互相转换



题目

难度等级:6(1-8难到易)

Some numbers have funny properties. For example:

89 --> 8¹ + 9² = 89 * 1

695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2

46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p

  • we want to find a positive integer k, if it exists, such that the sum of the digits of n taken to the successive powers of p is equal to k * n.

In other words:

Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k

If it is the case we will return k, if not return -1.

Note: n and p will always be given as strictly positive integers.

digPow(89, 1) shouldreturn1since8¹+9²=89=89*1

digPow(92, 1) shouldreturn-1sincethereisnoksuchas9¹+2²equals92*k

digPow(695, 2) shouldreturn2since6²+9³+5=1390=695*2

digPow(46288, 3) shouldreturn51since4³+6+2+8+8=2360688=46288*51

汉译

有些数字具有有趣的特性。例如:

89 --> 8¹ + 9² = 89 * 1

695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2

46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

给定一个正整数 n,写成 abcd...(a, b, c, d... 是数字)和一个正整数 p

  • 我们想要找到一个正整数 k,如果它存在的话,使得 n 的数字之和对 p 的连续幂等于 k  n。

换句话说:

是否存在整数 k 例如: (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k

如果是这种情况,我们将返回 k,如果不是,则返回 -1。

注意:n 和 p 将始终作为严格的正整数给出。

digPow(89, 1) shouldreturn1since8¹+9²=89=89*1

digPow(92, 1) shouldreturn-1sincethereisnoksuchas9¹+2²equals92*k

digPow(695, 2) shouldreturn2since6²+9³+5=1390=695*2

digPow(46288, 3) shouldreturn51since4³+6+2+8+8=2360688

代码区

classDigPow

{

public:

 staticintdigPow(intn, intp);

};

intdigPow(intn, intp) {

 // your code

}

解答

CPP(c++解法)

#include <cmath>

usingnamespacestd;

classDigPow

{

public:

 staticintdigPow(intn, intp){

  longlongsum=0;

  for(chardigit : to_string(n)){

    sum+=pow(digit-'0',p++);

  }

  return (sum/n)*n==sum?sum/n : -1;

 }

};

#include <string>

#include <cmath>

classDigPow

{

public:

 staticintdigPow(intn, intp);

};

intDigPow::digPow(intn, intp)

{

 longlongs=0;

 std::stringnstr=std::to_string(n);

 for (unsignedinti=0; i<nstr.length(); i++)

   s+=static_cast<longlong>(std::pow(static_cast<int>(nstr[i] -'0'), p+i));

 if (s%n==0)

   returns/n;

 else

     return-1;

}

#include <string>

#include <cmath>

usingnamespacestd;

classDigPow

{

public:

 staticintdigPow(intn, intp)

 {

   stringnum=to_string(n);

   inta{0};

 

   for(charch : num ) {

       inti=ch-'0';

       a+=pow(i, p);

       ++p;

     }

 

     return (( a%n==0) ?a/n : -1);

 }

};

C(c语言解法)

intdigPow(intn, intp) {

 intnumDigits=floor(log10(n))+1;

 intresult=0;

 intnum=n;

 for (inti=p+numDigits-1; i>=p; i--) {

   result+=pow(num%10, i);

   num/=10;

 }

 if (result%n==0) {

   returnresult/n;

 }

 return-1;

}

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <math.h>


int digPow(int n, int p) {

  long long sum = 0;

  char* s = malloc(20);

  sprintf(s, "%d", n);

  for(int i = 0; i < strlen(s); i++) {

    sum += pow(s[i] - '0', p + i);

  }

  return (sum / n) * n == sum ? sum / n : -1;

}

int digPow(int n, int p) {

 p += (int)log10(n);

 unsigned int val = n;

 unsigned int sum = 0;

 while(val > 0) {

   sum += pow(val % 10, p--);

   val /= 10;

 }

 return sum % n == 0 ? sum / n : -1;

}

D(我的解法)

#include<iostream>

#include <string>  

#include<math.h>

using namespace std;


int digPow(int n, int p)

{

string intStr = to_string(n);

long sum = 0;

for (int i = 0; i < intStr.length(); ++i, ++p) {

sum += pow(intStr[i] - '0', p);

}

return (sum % n == 0) ? sum / n : -1;

}


int main()

{

int n , p;

cin >> n; cin >> p;

cout<<digPow(n, p);

system("pause");

return 0;

}

PS(知识补充)

pow()

使用说明:实现次方运算^

头文件:#include<math.h>

使用方法:pow(a,b)

C++中int和string的互相转换

一、用sstream类

1. int -> string

#include<iostream>

#include<sstream>      //需要引用的头文件

using namespace std;


int main(){

   int x = 1234;        //需要转换的数字

   stringstream sstr;

   string str;


   sstr<<x;

   str = sstr.str();    //转换后的字符串

   cout << str <<endl;

   return 0;

}

2. string -> int

#include<iostream>

#include<sstream>      //需要引用的头文件

using namespace std;


int main(){

   int x;

   string str = "4321";  //需要转换的字符串

   stringstream sstr(str);


   sstr >> x;            //转换后的数字

   cout << x << endl;

}

缺点:处理大量数据时候速度慢;stringstream不会主动释放内存。

二、用sprintf、sscanf函数

1. int -> string

#include<iostream>

using namespace std;


int main(){

   int x = 1234;    //需要转换的数字

   string str;

   char ch[5];      //需要定义的字符串数组:容量等于数字长度+1即可


   sprintf(ch,"%d", x);

   str = ch;         //转换后的字符串

   cout << str << endl;

}

2. string -> int、float

#include<iostream>

using namespace std;


int main(){

   char ch[10] = "12.34";    //需要转换的字符串

   int x;                    //转换后的int型

   float f;                  //转换后的float型


   sscanf(ch, "%d", &x);      //转换到int过程

   sscanf(ch, "%f", &f);      //转换到float过程


   cout << x << endl;

   cout << f << endl;

}

三、C标准库atoi, atof, atol, atoll(C++11标准) 函数

可以将字符串转换成int,double, long, long long 型

1. int -> string

itoa函数:定义:char *itoa(int value, char *string, int radix);参数:① value:需要转换的int型② string:转换后的字符串,为字符串数组③ radix:进制,范围2-36

(没run起来,一直报错,随后再补)

2. string -> int、double、long、long long

atoi函数:定义:int atoi(const char *nptr);double atof(const char *nptr);long atol(const char *nptr);long long atoll(const char *nptr);参数:① nptr:字符串数组首地址

#include<iostream>

#include<stdlib.h>      //需要引用的头文件

using namespace std;


int main(){

   int x;

   char ch[] = "4321";    //需要转换的字符串

   x = atoi(ch);          //转换后的int数字


   cout << x << endl;

}

C++中int与char相互转换

一、ASCII表

了解int与char相互转换之前,先让我们看一下ASCII表。

网络异常,图片无法展示
|

其中数字字符对应的位置为:48(0) - 57(9)。

二、char转int

char转int之前,先将运算式中的每个字符都转换成ASCII码值,再进行计算。以下代码为例,其中i3的结果符合我们的预期要求。

charc='0';

inti1=c;                    // 48

inti2=c-0;                // 48

inti3=c-'0';              // 0

inti4=c+'0';              // 96

三、int转char

int转char之前,先将运算式中的每个字符都转换成ASCII码值,再进行计算。计算出数值后,再据此转换为字符(数值为该字符对应的ASCII码值)。以下代码为例,其中c4的结果符合我们的预期要求。

inti=5;

charc1=i;                  // 越界

charc2=i-0;              // 越界

charc3=i-'0';            // 越界

charc4=i+'0';            // 5

目录
相关文章
|
9月前
|
Go
go string to int 字符串与整数型的互换
go string to int 字符串与整数型的互换
46 0
|
2月前
|
Java UED
Java中String强转int:一种常见的错误和解决方法
在Java中将非数字字符串转换为整数会导致`NumberFormatException`。要解决这个问题,可以使用`try-catch`捕获异常,正则表达式验证数字格式,或利用异常信息提供错误提示。例如,`Integer.parseInt()`会因遇到非数字字符如`&quot;123abc&quot;`而抛出异常,但通过异常处理或正则`\\d+`可确保安全转换。记得在编程时避免直接强转,以防止程序异常中断。
|
2月前
|
存储 自然语言处理 安全
C++ STL标准库 《string原理与实战分析》
C++ STL标准库 《string原理与实战分析》
49 0
|
3月前
|
缓存 Java
Java中循环创建String对象的内存管理分析
Java中循环创建String对象的内存管理分析
54 2
|
8天前
|
Dart
Dart基础:进制转换、int与string互转
Dart基础:进制转换、int与string互转
41 3
遍历字符串,String line = xxx for(int i = 0;i<line.length();i++){system.out.println(line.chartAt(i)); 单个
遍历字符串,String line = xxx for(int i = 0;i<line.length();i++){system.out.println(line.chartAt(i)); 单个
|
2月前
|
Java
String转化为Int
String转化为Int
|
3月前
channelSftp.put(InputStream src, String dst, int mode);里的mode都是什么类型的
【5月更文挑战第15天】channelSftp.put(InputStream src, String dst, int mode);里的mode都是什么类型的
61 2
|
2月前
|
安全 Java 数据安全/隐私保护
Java基础4-一文搞懂String常见面试题,从基础到实战,更有原理分析和源码解析!(二)
Java基础4-一文搞懂String常见面试题,从基础到实战,更有原理分析和源码解析!(二)
29 0
|
2月前
|
JSON 安全 Java
Java基础4-一文搞懂String常见面试题,从基础到实战,更有原理分析和源码解析!(一)
Java基础4-一文搞懂String常见面试题,从基础到实战,更有原理分析和源码解析!(一)
50 0