Print histogram with "*" representing relative frequencies in C++ - c++

I'm trying to convert an histogram with absolute values to an histogram showing the relative frequency of letters in a string, written by the user. The letters frequency should be represented by *. So, if the letter "A" is 1% of a string, there should be two *. 1% = two *.
When trying to calculate the frequency, the output is zero. I don't really understand why.
I've tried to search the internet, but I can't really find something that helps me. I guess I'm stuck, both in my head and coding.
This is the code for my three functions:
void berakna_histogram_abs(const string inm, int arr[ANTAL_BOKSTAVER]){
int i, j = 0;
while (inm[i] != '\0'){
if (inm[i] >= 'a' && inm[i] <= 'z'){
j = inm[i] - 'a';
++arr[j];
}
if (inm[i] >= 'A' && inm[i] <= 'Z'){
j = inm[i] - 'A';
++arr[j];
}
i++;
}
}
void abs_till_rel(int arr[ANTAL_BOKSTAVER], int (&ree)[ANTAL_BOKSTAVER]){
for(int i = 0; i < ANTAL_BOKSTAVER; i++) {
ree[i] = arr[i] / 26;
printf("%c %lf \n", i + 'a', ree[i]);
}
for (int x = 0; x < ANTAL_BOKSTAVER; x++){
}
}
void plotta_histogram_rel(int (&ree)[ANTAL_BOKSTAVER]){
cout << "Frekvensen av bokstäver i texten är: " << endl;
for (int i = 0; i < ANTAL_BOKSTAVER; i++){
cout << char(i + 'a') << " : " << ree[i] << endl;
}
}
I'm not allowed to do any calculations in the third function, that is only for writing the histogram. The whole program is pretty big, if you'd like, I'll provide all the code.
Any help forward is much appreciated.
Thanks!

So, you have some errors that need to be corrected. You do not pass the array as reference in the first function. You pass it by value. So all modifications that will be done to that arra in the first function berakna_histogram_abs will not be visible to the outside world.
You need to do the same as in you other functions -->
void berakna_histogram_abs(const std::string inm, int (&arr)[ANTAL_BOKSTAVER]) {
By the way, the string should also be passed as reference. Anyway. Not so important.
Next problem. You forgot to initialize variable i to 0 in your first function. So, it will have some random value and the program will fail, becuase you access some random index with inm[i].
In your calculation function abs_till_rel you are using the wrong formular. You need to multiply with 100 to get integer results between 0 and 100 for the percentage. And you divide by 26, which makes the result relative to the amount of the number of letters in an alphabet. My guess is that you want to have the relations to the number of letters in the string.
For that, you first need to calculate all counts of letters to get the overall count. Like for example with:
int sum = 0;
for (int i = 0; i < ANTAL_BOKSTAVER; i++) sum += arr[i];
and then divide by this sum, like so:
ree[i] = (arr[i] * 100) / sum;
And to output the histogram, you can simply build a string with stars, using the std::string constructor number 2
Your updated program would look like this:
#include <iostream>
#include <string>
#include <stdio.h>
constexpr int ANTAL_BOKSTAVER = 26;
void berakna_histogram_abs(const std::string inm, int (&arr)[ANTAL_BOKSTAVER]) {
int i = 0, j = 0;
while (inm[i] != '\0') {
if (inm[i] >= 'a' && inm[i] <= 'z') {
j = inm[i] - 'a';
++arr[j];
}
if (inm[i] >= 'A' && inm[i] <= 'Z') {
j = inm[i] - 'A';
++arr[j];
}
i++;
}
}
void abs_till_rel(int arr[ANTAL_BOKSTAVER], int(&ree)[ANTAL_BOKSTAVER]) {
int sum = 0;
for (int i = 0; i < ANTAL_BOKSTAVER; i++) sum += arr[i];
if (sum >0) for (int i = 0; i < ANTAL_BOKSTAVER; i++) {
ree[i] = (arr[i] * 100) / sum;
std::cout << (char)(i + 'a') << '\t' << ree[i] << '\n';
}
for (int x = 0; x < ANTAL_BOKSTAVER; x++) {
}
}
void plotta_histogram_rel(int(&ree)[ANTAL_BOKSTAVER]) {
std::cout << "Frekvensen av bokstäver i texten är: " << std::endl;
for (int i = 0; i < ANTAL_BOKSTAVER; i++) {
std::cout << char(i + 'a') << " : " << std::string(ree[i]*2,'*') << std::endl;
}
}
int main() {
std::string test{"The quick brown fox jumps over the lazy dog"};
int frequencyArray[ANTAL_BOKSTAVER] = {};
int frequencyInPercent[ANTAL_BOKSTAVER] = {};
berakna_histogram_abs(test, frequencyArray);
abs_till_rel(frequencyArray, frequencyInPercent);
plotta_histogram_rel(frequencyInPercent);
}
But in C++, we would use the standard approach and write the followin:
#include <iostream>
#include <map>
#include <string>
#include <cctype>
// Our test string. This is a standard test string that contains all letters
std::string test{ "The quick brown fox jumps over the lazy dog" };
int main() {
// Count all letters
std::map<char, size_t> counter{};
for (const auto& c : test) if (std::isalpha(c)) counter[std::tolower(c)]++;
// Show histogram
for (const auto& [letter, count] : counter)
std::cout << letter << '\t' << std::string((count * 200) / test.size(), '*') << '\n';
return 0;
}

void abs_till_rel(int arr[ANTAL_BOKSTAVER], int langd, double frekArr[ANTAL_BOKSTAVER]){
//Function to calculate the relative frequency of letters in a string.
for (int i = 0; i < ANTAL_BOKSTAVER; i++){
frekArr[i] = arr[i]; //Writes over the input from the user to a new array.
frekArr[i] = frekArr[i] * 200 / langd; //Calculates the relative frequency
//*200 since 1% should be represented by two (2) *.
}
}
void plotta_histogram_rel(double frekArr[ANTAL_BOKSTAVER], int langd){
int j = 0;
for (int i = 0; i < ANTAL_BOKSTAVER; i++){
cout << char(i + 'A') << " : ";
//Creates a histograg, horizontal, with A-Z.
if(frekArr[i] > 0){
for ( j = 0; j < frekArr[i]; j++){
cout << "*";
}
cout << endl;
}
//If the index in frekArr is NOT empty, loop through the index [i] times and
//write double the amount of *.
else {
cout << " " << endl;
//Else, leave it empty.
}
}
}
I've solved the issue. See the working code above.

Related

I have to do a program that do a square in c++ with incremental letter

Hello and thank you for coming here.
I have to do a program that will draw a number of square choosed by the user with incremental letter.
For example, if the user choose 4 square, it will return :
DDDDDDD
DCCCCCD
DCBBBCD
DCBABCD
DCBBBCD
DCCCCCD
DDDDDDD
At the time being, my code look like this ;
#include <iostream>
using namespace std;
int main()
{
int size;
int nbsquareletter;
cout << " How many square ?" << endl;
cin >> nbsquareletter;
size = nbsquareletter * 2 - 1;
char squareletter = 'a';
for (int row = 1; row <= size; ++row)
{
for (int col = 0; col <= size; ++col)
{
if (row < col) {
cout << (char)(squareletter + row - 1) << " ";
}
else if (row > col)
{
cout << (char)(squareletter + col) << " ";
}
/*
cout << col << " ";
cout << row << " ";
*/
}
cout << endl;
}
}
If you have any ideas to help me, don't hesitate, I'm struggling. it's been 3.5 hours. Thanks you for reading and have a good day !
Try to keep things simple. If you start write code before you have a clear idea of how to solve it you will end up with convoluted code. It will have bugs and fixing them will make the code even less simple.
Some simple considerartions:
The letter at position (i,j) is determined by the "distance" from the center. The distance is max(abs(i - i_0), abs(j - j_0).
The center is at (i,j) = (size-1,size-1) when we start to count at upper left corner (0,0).
The letters can be picked from an array std::string letters = "ABCDEFG...".
i and j are in the range [0,2*size-1)
Just writing this (and nothing more) down in code results in this:
#include <iostream>
#include <string>
void print_square(int size){
std::string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i_0 = size-1;
int j_0 = size-1;
for (int i=0;i< 2*size-1;++i){
for (int j=0;j< 2*size-1;++j) {
int index = std::max(std::abs(i-i_0),std::abs(j-j_0));
std::cout << letters[index];
}
std::cout << "\n";
}
}
int main() {
print_square(4);
}
Which produces output
DDDDDDD
DCCCCCD
DCBBBCD
DCBABCD
DCBBBCD
DCCCCCD
DDDDDDD
Your code cannot print the right output, because when row == col there is no output, and it misses the diagonal. I didnt look further than that.
Instead of fixing bugs in your code I decided to suggest you my own solution. Maybe some other answers will be related to bugs in your code.
On piece of paper I figured out 4 different formulas for 4 parts of a drawn picture, formulas computing what letter to take inside English alphabet. Afterwards I take this letter from array with alphabet.
Try it online!
#include <iostream>
int main() {
int n = 0;
std::cin >> n;
char const letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < 2 * n - 1; ++i) {
for (int j = 0; j < 2 * n - 1; ++j)
std::cout << letters[
i <= j && i + j < 2 * n - 1 ? n - i - 1 :
i <= j && i + j >= 2 * n - 1 ? j - n + 1 :
i > j && i + j < 2 * n - 1 ? n - j - 1 :
i > j && i + j >= 2 * n - 1 ? i - n + 1 : 25
];
std::cout << std::endl;
}
}
Input:
7
Output:
GGGGGGGGGGGGG
GFFFFFFFFFFFG
GFEEEEEEEEEFG
GFEDDDDDDDEFG
GFEDCCCCCDEFG
GFEDCBBBCDEFG
GFEDCBABCDEFG
GFEDCBBBCDEFG
GFEDCCCCCDEFG
GFEDDDDDDDEFG
GFEEEEEEEEEFG
GFFFFFFFFFFFG
GGGGGGGGGGGGG
Let's define some functions, to make the recurrence relation obvious.
std::vector<std::string> WrapInLetter(char letter, std::vector<std::string> lines)
{
for (auto & line : lines)
{
line.insert(line.begin(), letter);
line.insert(line.end(), letter);
}
std::size_t size = (lines.size() * 2) + 1;
std::string edge(size, letter); // A string formed of size copies of letter
lines.insert(lines.begin(), edge);
lines.insert(lines.end(), edge);
return lines;
}
std::vector<std::string> SquareLetter(char letter)
{
if (letter == 'A') return { "A" };
return WrapInLetter(letter, SquareLetter(letter - 1));
}
Now main just has to call that function and loop over the result.
int main()
{
std::cout << "How many square ?" << std::endl;
int size;
std::cin >> size;
for (auto line : SquareLetter('A' + size - 1))
{
std::cout << line << std::endl;
}
}

Count letters in string

Can someone help me.
for example I input
for x RandomName for y and
it needs to count each y letter in x word, and output should be.
a: 2
n: 1
d: 1
void counter(string x, string y)
{
int signs[100];
int amount = 0;
for (int i = 0; i < y.length(); i++)
{
signs[i] = y[i];
for (int j = 0; j < x.length(); j++)
{
if (x[i] == y[i])
{
amount++;
}
}
cout << y[i] << ":" << amount << endl;
}
}
There are several errors in you code:
You always compare x[i] to y[i] ignoring the j index completely, which means you will never count a letter that is not in the same place in both strings.
You have a signs array you assign values to, but never use it. Also, it has the size 100, but for what?
You never reset the amount variable after the internal loop, which means it will not count letter individually.
You have the right idea - two loops, one iterates over all letters in y the other over all letters in x.
Fix the indexes in the comparison, reset the amount to 0 after you print it, and get rid of signs, and you code should work.
You incrise amount every time you find a lettre that match the input, but the amount is the same for every letter taken in parameters. To fix it just create an array of amount for every letter in parameters.
#define max(a, b) ((a) > (b) ? (a) : (b))
#define pass ((void)0)
std::string x = "RandomName";
std::string y = "and";
int maxSize = max(x.size(), y.size());
char* letterList = (char*)_alloca(maxSize);
int used = 0;
for (int l1 = 0; l1 < y.size(); l1++) {
char letter = y.at(l1);
int count = 0;
for (int i = 0; i < maxSize; i++) {
if (letter == letterList[i]) {
continue;//Do not know if that is the right spelling
}
}
letterList[used] = letter;
used++;
for (int l2 = 0; l2 < x.size(); l2++) {
if (letter == x.at(l2)) { count++; }
}
std::cout << letter << " = " << count << std::endl;
}
Should do what you want

Checking if guessed string has a correct character at the wrong position

I want to generate a random string with letters a,b,c,d then let the user guess it.
My output should be which positions the user guessed correctly and how many letters the user guessed correctly but put them in the wrong position.
Current attempt:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int main()
{
char lettres[4] =
{
'a',
'b',
'c',
'd'
};
char rString[4];
int i = 0;
srand(time(0));
while (i < 4)
{
int temp = rand() % 4;
rString[i] = lettres[temp];
i++;
}
int u = 0;
char t[4];
while (u < 10)
{
cout << "Enter your guess:\n ";
cin >> t;
for (int z = 0; z < 4; z++)
{
cout << rString[z] << ", "; //printing random string
}
cout << "\n";
int k;
int compteur = 0;
int t2[4];
int compteur2 = 0;
for (k = 0; k < 4; k++)
{
if (rString[k] == t[k]) //rString is my random string
{
t2[compteur2] = k;
compteur2++;
}
}
for (int y = 0; y < 4; y++)
for (int j = 0; j < 4; j++)
{
if (t[y] == rString[j] && y != j) //checking correct letters at wrong positions
{
compteur++;
t[y] = 'z'; //I put this line to avoid counting a letter twice
}
}
if (compteur2 == 4)
{
cout << "bravo\n";
u = 10;
} else
{
cout << "Positions with correct letters:\n ";
if (compteur2 == 0)
{
cout << "None";
cout << " ";
} else
for (int z = 0; z < compteur2; z++)
c out << t2[z] << ", ";
cout << " \n";
cout << "You have a total of " << compteur << " correct letters in wrong positions\n";
}
u++;
}
return 1;
}
Sample output:
Enter your guess:
abcd
b, a, b, a, //note this is my random string I made it print
Positions with correct letters:
None
You have a total of 1 correct letters in wrong positions
for example here I have 2 correct letters in the wrong position and I am getting 1 as an output
To clarify more about why I put t[y]='z'; if for example the random string was "accd" and my input was "cxyz" I would get that I have 2 correct letters at wrong positions, so I did that in attempt to fix it.
Any help on how to do this?
You should implement like this
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int main() {
srand(time(0));
char lettres[4] = {'a','b','c','d'};
char rString[4];
int i = 0;
//making random string
while (i < 4) {
int temp = rand() % 4;
rString[i] = lettres[temp];
i++;
}
int u = 0;
char t[4];
while (u < 10) {
cout << "Enter your guess:\n ";
cin >> t;
//printing random string
for (int z = 0; z < 4; z++) {
cout << rString[z] << ", ";
}
cout << "\n";
int correctPositions = 0;
cout << "Correct Position Are:\n";
for (int z = 0; z < 4; z++) {
if (rString[z] == t[z]) {
cout << (z + 1) << ", ";
correctPositions++;
}
}
if (correctPositions == 4) {
cout << "\nBingo!" << "\nThat's Right!";
return 0;
}
if (correctPositions == 0) {
cout << "None";
}
cout << "\n";
//finding no of correct letters in wrong position:
int correctLetters = 0;
for (int i = 0; i < 4; i++) {
char c = lettres[i];
int randomCount = 0;
int guessCount = 0;
int letterInCorrectPos = 0;
for (int z = 0; z < 4; z++) {
if (rString[z] == c) {
randomCount++;
}
if (t[z] == c) {
guessCount++;
}
if (rString[z] == t[z] && t[z] == c)
letterInCorrectPos++;
}
correctLetters += min(guessCount, randomCount) - letterInCorrectPos;
}
cout << "No. of correct letters but in wrong position :" << correctLetters;
cout << "\n\n";
u++;
}
return 0;
}
Explaining Logic
1. Finding No. Of Correct Positions:
This is done by iterating with z = 0 -> z=4 over the rString and t if rString[z] is t[z] (the char at z are matching) then we just print the position!
2. Finding No. Of Correct Letters In Wrong Position
This part was little tricky to implement but here is the method I followed.
We have lettres[] array which is containing all the letters, right? We will now individual loop over each letter in the array and count the no. of occurrence in the rString and t, and store the respective counts in a randomCount and guessCount respectively.
Ex. let rString = "bdcc" and t = "abcd" so we have the following data:
'a': randomCount:0 guessCount:1 letterInCorrectPos: 0
'b': randomCount:1 guessCount:1 letterInCorrectPos: 0
'c': randomCount:2 guessCount:1 letterInCorrectPos: 1
'd': randomCount:1 guessCount:1 letterInCorrectPos: 0
This is the first part in the above loop you can see we have another variable letterInCorrectPos, this variable stores the no. of instances in the string where, the letter is at the same position in both the strings.
Figuring these three values we can calculate the no. of correct letter:
correctLetters = min(guessCount, randomCount)
the smaller value of guessCount or randomCount is chosen because we don't want repeated counting. (We can't have more correct letters than there are instances of that letter in another class).
Now by simple logic: correct letters in wrong place is (correct letters) - (correct letters in the correct place ).Hence,
correctLetters = min(guessCount, randomCount) - letterInCorrectPos;
Since we are iterating in a loop and we want to add correctLetters of each letter, we use this statement at the end of loop:
correctLetters += min(guessCount, randomCount) - letterInCorrectPos;
Hope this will explain the working.

Frequency of Chars

I'm close to finishing my code! I could use some assistance, I've wrote a program that will count the number of letters in a string. My problem comes at the end, when outputting my data. say I enter the string "AAAABBBC"
My expected output should be
A-4
B-3
C-1
instead I get
C-4
C-3
C-1
any help would be appreciated, my code below
#include <iostream>
using namespace std;
class moose
{
char inputbuffer[122];
char countbuffer[122];
long count;
short index = 0;
public:
char charcount();
char charinput();
char initialize();
};
int main()
{
moose obj;
obj.initialize();
obj.charinput();
obj.charcount();
system("pause");
}
char moose::initialize()
{
for (int i = 0; i < 122; i++)
countbuffer[i] = 0;
return 0;
}
char moose::charinput()
{
cout << "Enter your text and I'll read your characters" << endl;
cin.getline(inputbuffer, 132);
cin.gcount();
count = cin.gcount();
count--;
return 0;
}
char moose::charcount()
{
for (int i = 0; i < count; i++)
{
if (inputbuffer[i] >= 'a' & inputbuffer[i] <= 'z' || inputbuffer[i] >= 'A' & inputbuffer[i] <= 'Z' || inputbuffer[i] > '0' & inputbuffer[i] <= '9'){
index = inputbuffer[i];
countbuffer[index]++;
}
}
for (int i = 0; i <= 122; i++) {
if (countbuffer[i] > 0)
{
cout << char(index) << " - " << int(countbuffer[i]) << endl;
}
}
return 0;
}
char moose::charcount()
{
for (int i = 0; i < count; i++)
{
if (inputbuffer[i] >= 'a' && inputbuffer[i] <= 'z' || inputbuffer[i] >= 'A' && inputbuffer[i] <= 'Z' || inputbuffer[i] > '0' && inputbuffer[i] <= '9'){
index = inputbuffer[i];
countbuffer[index]++;
}
}
for (int i = 0; i <= 122; i++) {
if (countbuffer[i] > 0)
{
cout << char(i) << " - " << int(countbuffer[i]) << endl;
}
}
return 0;
}
Print "i" in place of index.
& - bitwise-AND, use &&
Modify the last loop like in the following:
for (int i = 0; i <= 122; i++) {
if (countbuffer[i] > 0)
{
cout << char(i) << " - " << int(countbuffer[i]) << endl;
}
}
And convert bitwise ands to logical ands in the first loop (use &&).
By the way, in your case it is better to use a STL container like unordered_map, since you are going to build a histogram of characters actually. If you are going to store the frequency for a few characters in general, it is wasteful to allocate an array indexed by all possible characters, since a lot of the entries will be 0 in the end.

C++ binary input as a string to a decimal

I am trying to write a code that takes a binary number input as a string and will only accept 1's or 0's if not there should be an error message displayed. Then it should go through a loop digit by digit to convert the binary number as a string to decimal. I cant seem to get it right I have the fact that it will only accept 1's or 0's correct. But then when it gets into the calculations something messes up and I cant seem to get it correct. Currently this is the closest I believe I have to getting it working. could anyone give me a hint or help me with what i am doing wrong?
#include <iostream>
#include <string>
using namespace std;
string a;
int input();
int main()
{
input();
int decimal, x= 0, length, total = 0;
length = a.length();
// atempting to make it put the digits through a formula backwords.
for (int i = length; i >= 0; i--)
{
// Trying to make it only add the 2^x if the number is 1
if (a[i] = '1')
{
//should make total equal to the old total plus 2^x if a[i] = 1
total = total + pow(x,2);
}
//trying to let the power start at 0 and go up each run of the loop
x++;
}
cout << endl << total;
int stop;
cin >> stop;
return 0;
}
int input()
{
int x, x2, count, repeat = 0;
while (repeat == 0)
{
cout << "Enter a string representing a binary number => ";
cin >> a;
count = a.length();
for (x = 0; x < count; x++)
{
if (a[x] != '0' && a[x] != '1')
{
cout << a << " is not a string representing a binary number>" << endl;
repeat = 0;
break;
}
else
repeat = 1;
}
}
return 0;
}
I don't think that pow suits for integer calculation. In this case, you can use shift operator.
a[i] = '1' sets the value of a[i] to '1' and return '1', which is always true.
You shouldn't access a[length], which should be meaningless.
fixed code:
int main()
{
input();
int decimal, x= 0, length, total = 0;
length = a.length();
// atempting to make it put the digits through a formula backwords.
for (int i = length - 1; i >= 0; i--)
{
// Trying to make it only add the 2^x if the number is 1
if (a[i] == '1')
{
//should make total equal to the old total plus 2^x if a[i] = 1
total = total + (1 << x);
}
//trying to let the power start at 0 and go up each run of the loop
x++;
}
cout << endl << total;
int stop;
cin >> stop;
return 0;
}
I would use this approach...
#include <iostream>
using namespace std;
int main()
{
string str{ "10110011" }; // max length can be sizeof(int) X 8
int dec = 0, mask = 1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str[i] == '1') {
dec |= mask;
}
mask <<= 1;
}
cout << "Decimal number is: " << dec;
// system("pause");
return 0;
}
Works for binary strings up to 32 bits. Swap out integer for long to get 64 bits.
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
string getBinaryString(int value, unsigned int length, bool reverse) {
string output = string(length, '0');
if (!reverse) {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << i)) != 0) {
output[i] = '1';
}
}
}
else {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << (length - i - 1))) != 0) {
output[i] = '1';
}
}
}
return output;
}
unsigned long getInteger(const string& input, size_t lsbindex, size_t msbindex) {
unsigned long val = 0;
unsigned int offset = 0;
if (lsbindex > msbindex) {
size_t length = lsbindex - msbindex;
for (size_t i = msbindex; i <= lsbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << (length - offset));
}
}
}
else { //lsbindex < msbindex
for (size_t i = lsbindex; i <= msbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << offset);
}
}
}
return val;
}
int main() {
int value = 23;
cout << value << ": " << getBinaryString(value, 5, false) << endl;
string str = "01011";
cout << str << ": " << getInteger(str, 1, 3) << endl;
}
I see multiple misstages in your code.
Your for-loop should start at i = length - 1 instead of i = length.
a[i] = '1' sets a[i] to '1' and does not compare it.
pow(x,2) means and not . pow is also not designed for integer operations. Use 2*2*... or 1<<e instead.
Also there are shorter ways to achieve it. Here is a example how I would do it:
std::size_t fromBinaryString(const std::string &str)
{
std::size_t result = 0;
for (std::size_t i = 0; i < str.size(); ++i)
{
// '0' - '0' == 0 and '1' - '0' == 1.
// If you don't want to assume that, you can use if or switch
result = (result << 1) + str[i] - '0';
}
return result;
}