Straight-line Number
Last Updated :
06 May, 2021
Given a number N, the task is to check if N is an Straight-line Number or not. If N is an Straight-line Number then print “Yes” else print “No”.
A straight-line Number is a number greater than 99 in which the digits form an Arithmetic Progression.
Examples:
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
Approach: The idea is to convert the given number N into a string and check, if differences between consecutive digits are same or not. If the difference between all the corresponding digit are same then print “Yes” else print “No”.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isStraighLineNum( int N)
{
if (N <= 99)
return false ;
string str = to_string(N);
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 ;
}
int main()
{
int N = 135;
if (isStraighLineNum(n))
cout << "Yes" ;
else
cout << "No" ;
}
|
Java
class GFG{
static boolean isStraighLineNum( int N)
{
if (N <= 99 )
return false ;
String s = Integer.toString(N);
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 ;
}
public static void main(String[] args)
{
int n = 135 ;
if (isStraighLineNum(n))
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
def isStraighLineNum(N):
if (N < = 99 ):
return False ;
str1 = str (N);
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 ;
N = 135 ;
if (isStraighLineNum(N)):
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG{
static bool isStraighLineNum( int N)
{
if (N <= 99)
return false ;
string s = N.ToString();
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 ;
}
public static void Main()
{
int n = 135;
if (isStraighLineNum(n))
{
Console.Write( "Yes" );
}
else
{
Console.Write( "No" );
}
}
}
|
Javascript
<script>
function isStraighLineNum(N)
{
if (N <= 99)
return false ;
let s = N.toString();
let d = s[1] - s[0];
for (let i = 2; i < s.length; i++)
if (s[i] - s[i - 1] != d)
return false ;
return true ;
}
let n = 135;
if (isStraighLineNum(n))
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Time Complexity: O(log10N)
Share your thoughts in the comments
Please Login to comment...