stringtoint.cpp

来自「datastucutre and algorithms, application」· C++ 代码 · 共 41 行

CPP
41
字号

// convert a string into a nonnegative int that depends on all
// characters of the string

#include <iostream>
#include <string>

using namespace std;


int stringToInt(string s)
{// Convert s into a nonnegative int that depends on all
 // characters of s.
   int length = (int) s.length();   // number of characters in s
   int answer = 0;
   if (length % 2 == 1)
   {// length is odd
      answer = s.at(length - 1);
      length--;
   }

   // length is now even
   for (int i = 0; i < length; i += 2)
   {// do two characters at a time
      answer += s.at(i);
      answer += ((int) s.at(i + 1)) << 8;
   }

   return (answer < 0) ? -answer : answer;
}

// test program 
void main(void)
{
    string s = "abc";
    cout << s << " = " << stringToInt(s) << endl;

    s = "abcde";
    cout << s << " = " << stringToInt(s) << endl;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?