给定数字N ,任务是检查N是否为直线数。如果N是直线数,则打印“是”,否则打印“否” 。
A straight-line Number is a number greater than 99 in which the digits form an Arithmetic Progression.
例子:
Input: N = 135
Output: Yes
Explanation:
The digits of the number N are 1, 3, and 5.
1 3 5 is an AP with d = 2
Input: N = 136
Output: No
方法:想法是将给定数字N转换为字符串,并检查连续数字之间的差异是否相同。如果所有对应数字之间的差异相同,则打印“是”,否则打印“否” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if N is a
// Straight Line number or not
bool isStraighLineNum(int N)
{
// N must be > 99
if (N <= 99)
return false;
string str = to_string(N);
// Difference between consecutive
// digits must be same
int d = str[1] - str[0];
for (int i = 2; i < str.length(); i++)
if (str[i] - str[i - 1] != d)
return false;
return true;
}
// Driver Code
int main()
{
// Given Number N
int N = 135;
// Function Call
if (isStraighLineNum(n))
cout << "Yes";
else
cout << "No";
}
Java
// Java program for the above approach
class GFG{
// Function to check if N is a
// Straight Line number or not
static boolean isStraighLineNum(int N)
{
// N must be > 99
if (N <= 99)
return false;
String s = Integer.toString(N);
// Difference between consecutive
// digits must be same
int d = s.charAt(1) - s.charAt(0);
for(int i = 2; i < s.length(); i++)
if (s.charAt(i) - s.charAt(i - 1) != d)
return false;
return true;
}
// Driver code
public static void main(String[] args)
{
// Given Number N
int n = 135;
// Function Call
if (isStraighLineNum(n))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}
}
// This code is contributed by Pratima Pandey
Python3
# Python3 program for the above approach
# Function to check if N is a
# Straight Line number or not
def isStraighLineNum(N):
# N must be > 99
if (N <= 99):
return False;
str1 = str(N);
# Difference between consecutive
# digits must be same
d = int(str1[1]) - int(str1[0]);
for i in range(2, len(str1)):
if (int(str1[i]) -
int(str1[i - 1]) != d):
return False;
return True;
# Driver Code
# Given Number N
N = 135;
# Function Call
if (isStraighLineNum(N)):
print("Yes");
else:
print("No");
# This code is contributed by Code_Mech
C#
// C# program for the above approach
using System;
class GFG{
// Function to check if N is a
// Straight Line number or not
static bool isStraighLineNum(int N)
{
// N must be > 99
if (N <= 99)
return false;
string s = N.ToString();
// Difference between consecutive
// digits must be same
int d = s[1] - s[0];
for(int i = 2; i < s.Length; i++)
if (s[i] - s[i - 1] != d)
return false;
return true;
}
// Driver code
public static void Main()
{
// Given Number N
int n = 135;
// Function Call
if (isStraighLineNum(n))
{
Console.Write("Yes");
}
else
{
Console.Write("No");
}
}
}
// This code is contributed by Code_Mech
输出:
Yes
时间复杂度: O(log 10 N)