按升序打印包含数字 1、2 和 3 的数组


在此,任务是打印一个数组中的数字,其中包含 1、2 和 3 作为数字中的数字,如果没有这样的数字,则输出必须为 -1

Input : arr[] = {320,123,124,125,14532,126,340,123400,100032,13,32,3123,1100}
Output : 123 3123 14532 100032 123400

Since the array have values with digits 1, 2 and 3 it wouldn’t return -1 and print 5 values that
Contain 1, 2 and 3 in their respective numbers.

算法

START
Step 1 -> Declare array with elements of int type as arr
Step 2 -> store size of array in int n
Step 3 -> declare int variable as one, two, three
Step 4 -> call sort functions with parameters as arr and arr+n
Step 5 -> declare variable of type osrtingstream as st and string as num
Step 6 -> Loop For i=0 and i<n and ++i
   Set one=two=three=1
   Print arr[i]
   Set num=st.str()
   Set one=num.find("1")
   Set two=num.find("2")
   Set three=num.find("3")
   IF((one!=-1)&&(two!=-1)&&(three!=-1))
      Print num
   End
   Call st.str(‘’”)
end
STOP

示例

#include <bits/stdc++.h>
#include<string.h>
#include<sstream>
using namespace std;
int main() {
   int arr[] = {320,123,124,125,14532,126,340,123400,100032,13,32,3123,1100};
   int n = sizeof(arr)/sizeof(arr[0]);
   int one,two,three;
   sort(arr, arr+n);
   ostringstream st;
   string num;
   for (int i = 0; i < n; ++i) {
      one=two=three=-1;
      st << arr[i];
      num=st.str();
      one=num.find("1");
      two=num.find("2");
      three=num.find("3");
      if((one!=-1)&&(two!=-1)&&(three!=-1)) {
         cout<<num<<" ";
      }
      st.str("");
   }
}

输出

如果我们运行上面的程序,它会生成以下输出

123 3123 14532 100032 123400

更新于:2019 年 7 月 30 日

629 人浏览

启动你的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.